开发者

RoR: Creating an Object with string primary_key (associated error: Couldn't find Object_Id with ID=0)

开发者 https://www.devze.com 2023-01-20 14:18 出处:网络
I created a model that had a string primary_key. The Create action in Ruby on Rails gave me the following error:

I created a model that had a string primary_key.

The Create action in Ruby on Rails gave me the following error:

Couldn't find Theme with ID=0

My Theme table has no ID column, but a string column called name which is the primary key.

After searching everywhere, I experimented myself with the Create action inside the theme_controller.

It initially was:

def create
    @theme = Theme.new(params[:theme])

    respond_to do |format|
      if @theme.save
    ....

The :name parameter was being correctly passed, but was not being used, it was being replaced by an ID which my model does not have.

The solution was to insert the following line to force RoR to take the name into the obj开发者_JAVA技巧ect.

def create
    @theme = Theme.new(params[:theme])
    @theme.name = params[:theme][:name]
    respond_to do |format|
      if @theme.save
    ....


You should probably set the primary key in the model of Theme. Like

set_primary_key :name

and also disable id's in the migration like

create_table :themes, :id => false do |t|

Please also see http://roninonrails.blogspot.com/2008/06/using-non-standard-primary-keys-with.html for more information on the same. The approach you have is not required as Theme.new(params[:theme]) is supposed to automatically fill all the attributes in the model if the params[:theme] has the same attributes as that of the model. Not sure why its not working that way.

0

精彩评论

暂无评论...
验证码 换一张
取 消