简体   繁体   中英

has_many and has_one associations

There are two models:

  1. T
  2. TGroup

TGroup object may have many T objects. TGroup object has one favorite T object.

I want to define associations that will provide me the following functionality:

  1. TGroup.first.ts # will return list of T objects belong to TGroup.first object
  2. TGroup.first.favorite # will return the favorite T object of the TGroup.first object
  3. TGroup.first.ts << T.first # will attach T.first object to the TGroup.first object
  4. TGroup.first.favorite = T.first # will set the T.first object as the favorite of TGroup.first object

The solution I tried to implement was:

  1. Define t_group_id field (integer) on T
  2. Define favorite_id field (integer) on TGroup
  3. Define the following associations on TGroup model

has_many :ts, :class_name => T.to_s

has_one :t, :class_name => T.to_s, :foreign_key => :id, :primary_key => :favorite_id

I didn't succeed to define the "favorite" (should be something like ":as => :favorite"?) alias so I started with "t" instead. Unfortunately, doing that I can't set TGroup.first.t = T.first . Instead of setting the TGroup.first.t.id to T.first.id it makes changes on T model.

I think that what you need is a belongs_to association rather than a has_one one.

According to the docs the foreign key goes on the table for the class declaring the belongs_to association, so something like this should do the job:

belongs_to :favorite, :class_name => T.to_s

The has_one/belongs_to associations can be sometimes a bit confusing depending on each particular context.

Hope this helps.

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