acts_as_list 具有 has_and_belongs_to_many 关系
我发现了一个名为acts_as_habtm_list 的旧插件 - 但它适用于Rails 1.0.0。
这个功能现在内置在acts_as_list 中吗?我似乎找不到任何有关它的信息。
基本上,我有一个 Artist_events 表 - 没有模型。该关系是通过指定 :has_and_belongs_to_many 的这两个模型来处理的,
在这种情况下如何指定顺序?
I've found an old plugin called acts_as_habtm_list - but it's for Rails 1.0.0.
Is this functionality built in acts_as_list now? I can't seem to find any information on it.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设您有两个模型 - 艺术家和事件。
您希望他们之间有一种习惯关系,并且您希望能够为每个艺术家定义事件的顺序。
这是我的解决方案。我正在从我的脑海中编写这段代码,但类似的解决方案适用于我的情况。我很确定还有改进的空间。
我正在使用 Rails acts_as_list 插件。
这就是我定义模型的方式:
如您所见,您需要一个额外的模型 ArtistEvent,加入其他两个模型。 Artist_events 表应该有两个外部 ID 和附加列 - 位置。
之类的
现在您可以使用acts_as_list 方法(不幸的是,在ArtistEvent 模型上),但是Artist.find(:id).events
方法应该按正确的顺序为您提供属于特定艺术家的事件列表。
I'm assuming that you have two models - Artist and Event.
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.
I'm using rails acts_as_list plugin.
That's how I would define models:
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.
Now you can use acts_as_list methods (on ArtistEvent model, unfortunately) but something like
Artist.find(:id).events
should give you a list of events belonging to specific artist in correct order.
对已接受答案的附加更新:对于 Rails 4 和 Rails 5:
Additional update for the accepted answer: for Rails 4 and Rails 5:
我尝试像这样进行自我引用
但是字段 cross_sales.position 永远不会更新......
一个想法?
更新:好的,字段“id”在带有 has_many :through 选项的附加模型的情况下是必需的。现在运作良好
I trying with self-referencing like that
But the field cross_sales.position is never updated ...
An idea ?
Update: Ok the field 'id' it's necessary in the case of additional model with has_many :through option. It's work well now
在接受的答案中,请注意
:order => 'artist_events.position'
引用的是表artist_events
而不是模型。从
habtm
关联转移到has_many :through
时,我遇到了这个小问题。In the accepted answer, note that
:order => 'artist_events.position'
is referencing the tableartist_events
and not the model.I ran into this minor hiccup when moving from a
habtm
association tohas_many :through
.