开发者

ActiveRecord: Has many through (twice)

There are Things in Places which I'm looking to find. One Thing could be in many different Places, and many Things can be in one Place.

class Thing < ActiveRecord::Base
  has_and_belongs_to_many :places
end

class Place < ActiveRecord::Base
  has_and_belongs_to_many :things
end

I want to record the Finds of开发者_JAVA技巧 my Users so that I know where they found what.

class Find < ActiveRecord::Base
  belongs_to :user
  belongs_to :places_thing # Is this depluralization correct?
end

class User < ActiveRecord::Base
  has_many :finds
  # Now, how can I link in the Things the user has found? Like this?
  has_many :found_things_in_places, :class_name => :places_things, :through => :finds
  has_many :things, :through => :thought_things_in_places
end

Does this seem right? is it efficient? Thanks.


I think you were on the right track, the big change I'd make is that rather than having a join table (places_things) you should make it a proper model. I decided to call this an existence.

The data only exists in one place, so it's properly normalized. These relationships are clear and will be easy to manage. I think it's efficient.

class Place < ActiveRecord::Base
  has_many :existences
  has_many :things, :through => :existences
end

class Thing < ActiveRecord::Base
  has_many :existences
  has_many :places, :through => :existences
end

class Existence < ActiveRecord::Base
  belongs_to :place
  belongs_to :thing
end

class Find < ActiveRecord::Base
  belongs_to :user
  belongs_to :existence
end

class User < ActiveRecord::Base
  has_many :finds
  has_many :existences, :through => :finds
  has_many :things, :through => :existences
end

You'll need rails 3.1 to do the nested has many through's like we did in User.

BTW the correct association declaration should be: belongs_to :places_things

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜