【问题标题】:collection_select giving ActiveRecord::AssociationTypeMismatchcollection_select 给 ActiveRecord::AssociationTypeMismatch
【发布时间】:2012-11-13 06:17:57
【问题描述】:

我不确定我问的这个问题是对的,还是我太累了,以至于看不出来。

我的代码是:

_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 

切换一切,它的工作完美 - 我想我太累了:)

【问题讨论】:

    标签: ruby-on-rails forms collections


    【解决方案1】:

    你应该改变:

    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
    

    【讨论】:

    • 我收到错误:链接中的 NoMethodError#new undefined method `merge' for :name:Symbol
    • 您的模型中有外键category_id 吗?你用表格做什么?
    • 我进行了更改,但它仍然给了我合并错误 - 我更新以包含我的模型
    • 您在链接表中没有category_id 列?如果你有,你应该在你的模型中定义:attr_accessible :category_id,而不是attr_accessible :category
    • 哈哈 - 就是这样 - 我将我的数据库切换到 t.integer :category_id 并且它可以工作。
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多