Rails 表间关联时候 attr_accessible 该怎么写

hegwin · June 14, 2012 · Last by hegwin replied at June 15, 2012 · 3337 hits

最近用 rails3.2.3 遇到的问题,在这个论坛里看到好几个这样的帖子,但是也没看到解决的方法

用 generate 自动生成的 model 里 attr_accessible 后面都是那个 model 在数据库对应的表的字段,这个倒是好理解 比如说 product 里有 title 和 price

class Product < ActiveRecord::Base
  attr_accessible :title, :price
end

那如果是表间关联的时候(belongs_to),这个 attr_accessible 应该怎么写? 假设产品 (products) 和类别 (categories) 这样

class Product < ActiveRecord::Base
  attr_accessible :title, :price

  belongs_to :category
end
class Category < ActiveRecord::Base
  has_many :products
end

假设有如下代码

category = Category.find(:id)

Product.build(title: "title", price: 123, categoy: category)

直接这么写的话会报错: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: category

改环境里那个配置总觉得不太好。。。

class Product < ActiveRecord::Base
  attr_accessible :title, :price, :category 

  belongs_to :category
end

#1 楼 @chucai 啊 谢谢。。我脑子没转过湾来,被 API 迷惑了……

You need to Sign in before reply, if you don't have an account, please Sign up first.