具有has_and_belongs_to_many关系的acts_as_list

mcu*_*ulp 10 ruby-on-rails has-and-belongs-to-many ruby-on-rails-plugins acts-as-list

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

这个功能现在是在acts_as_list中构建的吗?我似乎无法找到任何相关信息.

基本上,我有一个artists_events表 - 没有模型.通过指定的两个模型处理关系:has_and_belongs_to_many

在这种情况下如何指定订单?

小智 22

我假设你有两个模特 - 艺术家和事件.

您希望在它们之间建立habtm关系,并且您希望能够为每个艺术家定义事件顺序.

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

我正在使用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
Run Code Online (Sandbox Code Playgroud)

如您所见,您需要一个额外的模型ArtistEvent,加入另外两个.artist_events表应该有两个外部ID和附加列 - 位置.

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

Artist.find(:ID).events

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

  • has_and_belongs_to_many被​​许多人视为已弃用.Join模型解决方案为您提供与habtm方法相同的功能,但更灵活. (3认同)