ActiveRecord:有很多通过(两次)

JP.*_*JP. 2 ruby activerecord

ThingS IN PlaceS的,我希望找到.一个Thing可以在许多不同的Places中,并且许多Things可以在一个中Place.

class Thing < ActiveRecord::Base
  has_and_belongs_to_many :places
end

class Place < ActiveRecord::Base
  has_and_belongs_to_many :things
end
Run Code Online (Sandbox Code Playgroud)

我想记录Find我的Users,以便我知道他们在哪里找到了什么.

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
Run Code Online (Sandbox Code Playgroud)

这看起来是对的吗?它有效吗?谢谢.

Luk*_*ell 5

我认为你走在正确的轨道上,我所做的重大改变是,你应该把它变成一个合适的模型而不是连接表(places_things).我决定称之为存在.

数据只存在于一个地方,因此它已正确规范化.这些关系很清晰,易于管理.我觉得它很有效率.

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
Run Code Online (Sandbox Code Playgroud)

你需要rails 3.1来做嵌套有很多像我们在用户那样做的.

BTW正确的关联声明应该是:belongs_to:places_things