Karan
Karan

Reputation: 15094

Rails: Add information in a many-to-many association

I have set up a many-to-many association between users and rotas. I am trying to also store who the creator of a particular rota is.

Class User

  has_many :rotazations
  has_many :rotas, :through => :rotazations

Class Rota

  has_many :rotazations
  has_many :users, :through => :rotazations, :order => 'name ASC'

Class Rotazation

  belongs_to :user
  belongs_to :rota

  before_create do |rotazation|
    rotazation.creator_id = rotazation.user_id
  end

When a rota is created, I have successfully set the creator_id in the rotazation table to have the id of the user who created the rota. My question is, how do I access it:

rota.creator

My attempt

I have tried to add the following:

Rota Class

...
belongs_to :creator, :class_name => "User", :through => :rotazations, :foreign_key => "creator_id"  
...

User Class

has_many :created_rotas, :class_name=> "Rota", :through => :rotazations, :foreign_key => "creator_id"  

However, this doesnt work. Any ideas how to achieve rota.creator work? Thanks!

Upvotes: 0

Views: 2980

Answers (1)

gabrielhilal
gabrielhilal

Reputation: 10769

Each time you create a new line in your rotazations table you add the user_id to the creator_id, which is an attribute on the Rotazation.

However, the rotazations table is a combination of user_id and rota_id just to solve the many-to-many relationship. If I am thinking it right, the creator_id will always be the same as user_id. So, you actually have redundante data:

| user_id | rota_id |creator_id |
| 1       | 1       | 1         |
| 2       | 1       | 2         |
| 1       | 2       | 1         |
| ...     | ...     | ...       |

In order to know who has created a new Rota you can add a new attribute to the rotas table, lets say creator.

When you create a new rota, you can save the user_id into this new attribute:

@rota = Rota.new
@rota.creator = current_user.id

Upvotes: 1

Related Questions