Active Record Associations: has_one :through? Or multiple has_one's?
I'm brand new to Rails, so bear with me.
I have 3 models: User, Section, and Tick.
Each section is created by a user. My guess with this association:
class Section < ActiveRecord::Base
has_one :user
end
Next, each user can "tick" off a section -- only once. So for each tick, I have a section_id, user_id, and timestamps. Here's where I'm stuck. Does this call for a "has_one :through" association? If so, which direction? If not, then I'm way off.
Which association works here?
Than开发者_如何学编程ks!
This should be right:
class User < AR::Base
has_many :sections #user can have many sections
has_many :ticks, :through => :sections #user has many ticks, but the left outer join goes through sections
end
class Section < AR::Base
belongs_to :user #each section belongs to 1 user
has_many :ticks #each section can have a tick, because of can use has_many
end
class Tick < AR::Base
belongs_to :section #a tick belongs to a section
has_one :user, :through => :sections #belongs_to :through does not exist, use has_one through
end
class User < AR::Base
has_many :ticks
has_many :sections, :through => :ticks
end
class Section < AR::Base
has_many :ticks
has_many :users, :through => :ticks
end
class Tick < AR::Base
belongs_to :user
belongs_to :section
validates_uniqueness_of :user_id, :scope => :section_id
end
Now to find the sections a user ticked you do user.sections
, or to find all users who ticked a certain section you do section.users
What you have here is a many-to-many relation (a user can have many sections, and a section can belong to many users), so this requires a join model to associate them. In this case, the Tick model is acting as the join model.
Try Following
class Tick < ActiveRecord::Base
belongs_to :user
belongs_to :section
validates_uniqueness_of :user_id, :scope => :section_id #There is only one user per section
end
Ref This
精彩评论