update_attributes的等价物是什么?

时间:2011-05-12 15:01:53

标签: ruby-on-rails

通常,当我向@announcement添加新产品时,我会这样做:

@announcement = Announcement.find(params[:id])
@announcement.products << Product.find_all_by_id(params[:announcement_products])

@announcement.products << Product.find_all_by_id(params[:announcement_products])执行update_attributes()相当于什么?

作为参考,我的模型定义如下:

MODEL

class Product < ActiveRecord::Base
  has_many :announcement_products
  has_many :announcements, :through => :announcement_products

  accepts_nested_attributes_for :announcements#, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

class Announcement < ActiveRecord::Base
  has_many :announcement_products
  has_many :products, :through => :announcement_products

  accepts_nested_attributes_for :products#, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

class AnnouncementProduct < ActiveRecord::Base
  belongs_to :announcement
  belongs_to :product
end

2 个答案:

答案 0 :(得分:2)

查找has_many为您提供的关联方法。其中有“association_ids =”,它需要一组id。这适用于update_attributes,因为如果你这样做

params = {:product => {:announcement_ids => [1,2,3]}}
@product.update_attributes(params[:product])

有效地做到了

@product.announcement_ids = [1,2,3]

这适用于表单中的复选框,例如将公告ID写入“product [announcement] []”。

答案 1 :(得分:2)

只需在附件中设置:product_ids即可。所以

{:announcement=>{:name=>"foo222", :description=>"bar", :product_ids => [8, 9]}}

正是您要找的。这可以通过复选框或在http请求中发送“数组”的任何其他内容来实现。

此外,如果您使用的是attr_accessible,请不要忘记将product_ids属性添加到列表中,只需记住在需要时注意质量分配。