具有has_and_belongs_to_many关系的acts_as_list [英] acts_as_list with has_and_belongs_to_many relationship

查看:121
本文介绍了具有has_and_belongs_to_many关系的acts_as_list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个名为act_as_habtm_list的旧插件-但这是针对Rails 1.0.0的.

I've found an old plugin called acts_as_habtm_list - but it's for Rails 1.0.0.

此功能现在内置在act_as_list中吗?我似乎找不到任何信息.

Is this functionality built in acts_as_list now? I can't seem to find any information on it.

基本上,我有一个artist_events表-没有模型.通过这两个指定:has_and_belongs_to_many

Basically, I have an artists_events table - no model. The relationship is handled through those two models specifying :has_and_belongs_to_many

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

How can I specify order in this situation?

推荐答案

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

I'm assuming that you have two models - Artist and Event.

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

You want to have an habtm relationship between them and you want to be able to define an order of events for each artist.

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

Here's my solution. I'm writing this code from my head, but similar solution works in my case. I'm pretty sure there is a room for improvement.

我正在使用rails actions_as_list插件.

I'm using rails acts_as_list plugin.

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

That's how I would define models:

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和附加列-位置.

As you see you need an additional model ArtistEvent, joining the other two. The artist_events table should have two foreign ids and additional column - position.

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

Now you can use acts_as_list methods (on ArtistEvent model, unfortunately) but something like

Artist.find(:id).events

Artist.find(:id).events

应该以正确的顺序为您提供属于特定歌手的事件列表.

should give you a list of events belonging to specific artist in correct order.

这篇关于具有has_and_belongs_to_many关系的acts_as_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆