Reputation: 19723
Normally, when I add a new product to an @announcement, I do:
@announcement = Announcement.find(params[:id])
@announcement.products << Product.find_all_by_id(params[:announcement_products])
What's the equivalent of doing @announcement.products << Product.find_all_by_id(params[:announcement_products])
for update_attributes()
?
As a reference, my model definition looks like:
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
Upvotes: 2
Views: 1082
Reputation: 1195
Just set :product_ids in the params for attachment. So
{:announcement=>{:name=>"foo222", :description=>"bar", :product_ids => [8, 9]}}
is what you are looking for. This can be achieved with checkboxes or anything else that sends an "array" in the http request.
Also, if you're using attr_accessible, don't forget to add the product_ids attribute to the list, just remember to look out for mass assignment if you need to.
Upvotes: 2
Reputation: 32955
Look up the association methods that has_many gives you. Among them are "association_ids=", which expects an array of ids. This works well with update_attributes, because if you do this
params = {:product => {:announcement_ids => [1,2,3]}}
@product.update_attributes(params[:product])
that effectively does
@product.announcement_ids = [1,2,3]
This works well with checkboxes in a form, writing announcement ids to "product[announcement][]" for example.
Upvotes: 2