0

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!

Karan
  • 14,824
  • 24
  • 91
  • 157
  • Have a look at this posts: [Many-To-Many relationship](https://stackoverflow.com/questions/2168442/many-to-many-relationship-with-the-same-model-in-rails) This accepted answer there has helped me out when I had a similar problem. – Automatico Jul 29 '12 at 13:51

1 Answers1

1

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
gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
  • very good point. So its a many-to-one relationship between a User and a Rota. I normally create rotas using: user.rotas.create I was wondering, can I implement a call back when the rota is created to automatically have the creator field point to the user that created it? – Karan Jul 29 '12 at 13:25
  • you can do `user.rotas.create` because of the has_many through association, otherwise you had to do it in parts as user and rota are not directly connected. I think the best option for you is to include a hidden_field in your form. I am assuming you have a current_user helper, so you can include `<% f.hidden_field :creator, :value => current_user.id %>`. Each time you create a new rota, the `creator` will store the `id` of the current user. – gabrielhilal Jul 29 '12 at 13:35