Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to many table with an extra column in Rails

Is it possible to do this with only two Rails models, User and Event:

Users
|id        |name         |age         |
|1         |danilo       |26          |
|2         |joe          |23          |
|3         |carlos       |50          |
|4         |katy         |45          |

Events_Users
|event_id     |user_id        |confirmed       |
|1            |1              |1               |
|3            |3              |0               |
|4            |3              |1               |
|2            |3              |1               |

Events
|id           |name                     |date            |
|1            |the end of the year      |31/12/2012      |
|2            |the end of the world     |21/12/2012      |
|3            |Party                    |18/12/2012      |
|4            |Dinner                   |19/12/2012      |

The problem is, the user can confirm or not their presence in an event, for this I used the table Events_Users, column confirmed (1 for confirmed). How can I do this with Rails ActiveRecord without an model "Event_User"? How can I manipulate the confirmed column in the User model?

I am using Rails 3.2.9 .

like image 281
danilodeveloper Avatar asked Dec 09 '12 22:12

danilodeveloper


1 Answers

User and Event have many-to-many relationship, you can not set up this association with just 2 model, you must have the join model, or join table.

In your case, you added attribute confirmed, so you will need a join model, named Confirmation (as other people recommended). Your define associations will be like this:

class User
  has_many :events, through: :confirmations
  has_many :confirmations
end

class Event
  has_many :users, through: :confirmations
  has_many :confirmations
end

class Confirmation
  belongs_to :user
  belongs_to :event
end
like image 125
Thanh Avatar answered Oct 03 '22 04:10

Thanh