ruby-on-rails - collection_select 给出 ActiveRecord::AssociationTypeMismatch

标签 ruby-on-rails forms collections

我不确定我问的这个问题是否正确,或者只是太累了,以至于不明显。

我的代码是:

_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 

把所有东西都换过来了,它工作得很完美——我想我太累了:)

最佳答案

你应该改变:

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

关于ruby-on-rails - collection_select 给出 ActiveRecord::AssociationTypeMismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13356322/

相关文章:

javascript - Antd 的 @Form.create<Props>() 装饰器导致不明确的 TypeScript 错误

java - Producer/Consumer——生产者无阻塞地向集合中添加数据,消费者批量消费集合中的数据

ruby-on-rails - 设计:注册失败时重定向?

ruby-on-rails - 如何将新的键值对插入到 Rails 4 中的获取数据库对象中

javascript - Adobe Acrobat Javascript 表单 - 在多个页面中显示/隐藏图层

java - 将类添加到 Collection 时出现 UnsupportedOperationException

java - 约束特定键 - HashMap 的约定 - Java

ruby-on-rails - Rails 应用程序中 Office 365 的 SMTP 设置

mysql - 我的连接表似乎不起作用

php - 需要我的 HTML 搜索表单来搜索在搜索表单上选择的选项,然后显示我的结果?