简体   繁体   中英

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?

Thanks!

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM