Ruby on Rails四向关联树 [英] Ruby on Rails four-way association tree
问题描述
大局:我正在创建一个应用程序来历史地跟踪时间事件.我使用四个主要模型进行设置:用户,事件,故事和图像.这个想法是,任何给定的用户都可以创建一个事件,并将故事和/或图像添加到他自己的事件或任何其他事件中.但是故事"和图像"总是附加到某个事件上,其他任何模型都属于创建该事件的用户(用于过滤和编辑)
The big picture: I am creating an app to track temporal events historically. I am setting it up with four main models: Users, Events, Stories and Images. The idea is that any given user can create an Event, and add Stories and/or Images to his own Event or to any other one. But both Stories and Images are always attached to a certain Event, and any other model belongs to the User who created it (for filtering and editing purposes)
关联的一般结构如下:
class User < ActiveRecord::Base
has_many :events
has_many :stories
has_many :images
end
class Event < ActiveRecord::Base
belongs_to :user
has_many :stories
has_many :images
end
class Story < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
class Image < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
我是Rails的新手,我几乎无法控制更复杂的关联,例如many_to_many,通过:或as:
I am kind of new to Rails and I have little-to-no control over more complex associations as many_to_many, through: or as:
我在这里的问题是,这组关联是最优的,还是可以通过以其他方式组合起来加以改进?
My question here is, is this set of associations optimal, or could it be improved by combining them in a different way?
推荐答案
您处于正确的轨道,但是story
和image
不应该属于user
.您将在其中创建冗余.
You're in the right track, but story
and image
shouldn't belong to user
. You're creating a redundancy in there.
class User < ActiveRecord::Base
has_many :events
has_many :stories, :through => :events
has_many :images, :through => :events
end
class Event < ActiveRecord::Base
belongs_to :user
has_many :stories
has_many :images
end
class Story < ActiveRecord::Base
belongs_to :event
end
class Image < ActiveRecord::Base
belongs_to :event
end
这样,您仍然可以编写user.stories
和user.images
.
This way you can still write user.stories
and user.images
.
这篇关于Ruby on Rails四向关联树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!