HABTM 通过复选框进行编辑

发布于 2024-09-14 06:58:20 字数 597 浏览 2 评论 0原文

我在出版物和类别之间有 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"

这显示得很好 - 不过,在更新时,它只保存最后一个检查的类别(如果我检查多个类别,则只保存一个类别),如果我不这样做不要选中任何框,它不会改变映射的内容。

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[category_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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你另情深 2024-09-21 06:58:20

我的问题-我必须在发布上实现一个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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文