HABTM through editing via checkboxes
I have a HABTM relationship between Publications and Categories. In the new and edit views, I have this:
Categories:<br />
<% @categories.each do |c| %>
<%= check_box_tag :category_ids, c.id, @publication.categories.include?(c), :name => 'publication[cate开发者_如何学JAVAgory_ids]' -%>
<%= "#{c.name}"%><br />
<% end -%>
The model code:
class Publication < ActiveRecord::Base
has_many :listings
has_many :categories, :through => :listings, :order => "listings.position"
This displays just fine - on update, though, it only saves the last category that is checked (if I check multiple categories, only one is saved), if I don't check any box, it doesn't change what's mapped.
My problem - I had to implement a category_ids setter on Publication. I implemented it as so:
after_save :update_categories
attr_accessor :category_ids
def update_categories
unless category_ids.nil?
self.listings.each do |listing|
listing.destroy unless category_ids.include?(listing.category_id.to_s)
category_ids.delete(listing.category_id.to_s)
end
category_ids.each do |cid|
self.listings.create(:category_id => cid) unless cid.blank?
end
reload
self.category_ids = nil
end
end
精彩评论