2012-11-13 51 views
3

我不知道我問這個問題是正確的,還是太累了,因爲它是顯而易見的。collection_select給ActiveRecord :: AssociationTypeMismatch

我的代碼是:

_form.html.haml

= f.collection_select :category, Category.where(:user_id => current_user.id), :id, :name 

我得到的是

ActiveRecord::AssociationTypeMismatch in LinksController#create 
Category(#70203963939880) expected, got String(#70203929255820) 

日誌被

Started POST "/links" for 127.0.0.1 at 2012-11-12 22:14:05 -0800 
Processing by LinksController#create as HTML 
Parameters: {"utf8"=>"✓", "authenticity_token"=>"z4RYcUW3hGLfKBAwQLMZbye2I1mn16fg6BSBGe7GILU=", "link"=>{"name"=>"SFGate", "url"=>"http://www.sfgate.com/", "category"=>"1"}, "commit"=>"Save"} 
Completed 500 Internal Server Error in 0ms 

看來好像它的消逝:id作爲一個字符串而不是一個整數。任何線索?

更新:

class Category < ActiveRecord::Base 
    belongs_to :user 
    has_many :links 

    attr_accessible :name, :color, :position 

    COLOR_CODES = ["Green", "Blue", "Yellow", "Orange", "Red", "Purple", "Pink"] 
end 

class Link < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :category 

    attr_accessible :category, :name, :position, :url, :user_id 
end 

修正:我有

t.integer :category 

,而不是

t.integer :category_id 

切換所做的一切和它的工作完美 - 我想我是太累了:)

回答

2

你應該改變:

f.collection_select :category, Category.where(:user_id => current_user.id), :id, :name 

到:

f.collection_select :category_id, Category.where(:user_id => current_user.id), :id, :name 
+0

我得到的錯誤:NoMethodError在鏈接#新的未定義的方法'合併」:名稱:符號 – jbolanos

+0

你有外鍵'category_id'您模型?你在做什麼? – Thanh

+0

@jbolanos我更新了我的答案,檢查它。 – Thanh

相關問題