HABTM通过复选框编辑

时间:2010-08-15 20:39:57

标签: ruby-on-rails has-and-belongs-to-many

我在出版物和类别之间有HABTM关系。在新视图和编辑视图中,我有:

Categories:<br />
<% @categories.each do |c| %>
  &nbsp;<%= check_box_tag :category_ids, c.id, @publication.categories.include?(c), :name => 'publication[category_ids]' -%>
  <%= "#{c.name}"%><br />
<% end -%>

型号代码:

class Publication < ActiveRecord::Base
   has_many :listings
   has_many :categories, :through => :listings, :order => "listings.position"

这显示很好 - 在更新时,它只保存检查的最后一个类别(如果我检查多个类别,只保存一个),如果我不检查任何框,它不会改变什么是映射。

1 个答案:

答案 0 :(得分:0)

我的问题 - 我必须在Publication上实现category_ids setter。我这样实现了它:

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