Ruby on Rails four-way association tree

拥有回忆 提交于 2019-12-12 02:09:30

问题


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)

The general structure of the associations would be something like this:

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

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?


回答1:


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

This way you can still write user.stories and user.images.




回答2:


Try to use nested attributes:

http://railscasts.com/episodes/196-nested-model-form-part-1

Sample code:

class User < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :stories
  has_many :images
  accepts_nested_attributes_for :stories, :images
end

class Story < ActiveRecord::Base
  belongs_to :event
end

class Image < ActiveRecord::Base
  belongs_to :event
end

Nested attributes accepts many level. In this case, there are 3 levels

  1. user

  2. event

  3. story and image.

It like the sample at rails cast with 3 level (survey - question -answer).

Look at the link above and watch the part 2 to see how it work.

Or you can't look at my sample, but it work with 2 levels(subject - task).

Link at here

Login with account: duyet.vn@gmail.com/12341234



来源:https://stackoverflow.com/questions/18648245/ruby-on-rails-four-way-association-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!