【问题标题】:acts_as_list with has_and_belongs_to_many relationship具有 has_and_belongs_to_many 关系的acts_as_list
【发布时间】:2010-02-16 17:35:28
【问题描述】:

我找到了一个名为acts_as_habtm_list 的旧插件 - 但它适用于 Rails 1.0.0。

现在这个功能是内置在acts_as_list 中的吗?我似乎找不到任何关于它的信息。

基本上,我有一个 Artists_events 表 - 没有模型。这种关系是通过指定 :has_and_belongs_to_many 的这两个模型来处理的

在这种情况下如何指定顺序?

【问题讨论】:

  • 您能说得更具体些吗?你到底想达到什么目的?您找到的插件的链接也很好。
  • 在寻找插件时,我发现了一个可能可以使用的新插件:github.com/SFEley/habtm_list 我正在尝试完成活动中艺术家的顺序 - 假设你去参加音乐会一个头条新闻和两个开场白。我想让它显示艺术家们演奏的顺序。

标签: ruby-on-rails ruby-on-rails-plugins has-and-belongs-to-many acts-as-list


【解决方案1】:

我假设您有两个模型 - Artist 和 Event。

您希望在他们之间建立一种习惯关系,并且您希望能够为每个艺术家定义事件的顺序。

这是我的解决方案。我正在从头开始编写此代码,但类似的解决方案适用于我的情况。我很确定还有改进的余地。

我正在使用 rails 的acts_as_list 插件。

这就是我定义模型的方式:

class Artist < ActiveRecord::Base
  has_many :artist_events
  has_many :events, :through => :artist_events, :order => 'artist_events.position'
end

class Event < ActiveRecord::Base
  has_many :artist_events
  has_many :artists, :through => :artist_events, :order => 'artist_events.position'
end

class ArtistEvent < ActiveRecord::Base
  default_scope :order => 'position'
  belongs_to :artist
  belongs_to :event
  acts_as_list :scope => :artist
end

如您所见,您需要一个附加模型 ArtistEvent,加入其他两个模型。 Artist_events 表应该有两个外来的 id 和额外的列 - 位置。

现在您可以使用acts_as_list 方法(不幸的是,在ArtistEvent 模型上)但类似

Artist.find(:id).events

应该以正确的顺序为您提供属于特定艺术家的事件列表。

【讨论】:

  • 我接受这个答案的唯一疑虑是我正在使用 :has_and_belongs_to_many 并且我没有模型。这段代码等效吗?
  • has_and_belongs_to_many 被许多人认为已弃用。加入模型解决方案为您提供与 habtm 方法相同的功能,但更加灵活。
  • 请参阅下面的 Tricia 更新。您必须在中间表中添加一个 :primary 才能使其正常工作。
【解决方案2】:

已接受答案的附加更新:Rails 4 和 Rails 5:

has_many :events, -> { order 'artist_events.position ASC' }, through: :artist_events
has_many :artists, -> { order 'artist_events.position ASC' }, through: :artist_events

【讨论】:

    【解决方案3】:

    我尝试这样的自我引用

    class Product < ActiveRecord::Base
      has_many :cross_sales
      has_many :cross_sales_products, :through => :cross_sales, :order => 'cross_sales.position'
    end
    
    class CrossSale < ActiveRecord::Base
      default_scope :order => 'cross_sales.position'
      belongs_to :product
      belongs_to :cross_sales_product, :class_name => "Product"
      acts_as_list :scope => :product
    end
    
    create_table :cross_sales, :force => true, :id => false do |t|
      t.integer :product_id, :cross_sales_product_id, :position
    end
    

    但字段 cross_sales.position 从未更新...

    一个想法?

    更新:好的,字段 'id' 在带有 has_many :through 选项的附加模型的情况下是必需的。现在效果很好

    【讨论】:

      【解决方案4】:

      在接受的答案中,请注意 :order =&gt; 'artist_events.position' 引用的是表 artist_events 而不是模型。

      我在从 habtm 关联移动到 has_many :through 时遇到了这个小问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多