A lot for a large table with an extra column in Rails

Hi guys! This can only be done with 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 that the user can confirm or not confirm his presence in the event, for this I used the Events_Users table, the confirmed column (1 for confirmed). How can I do this using Rails ActiveRecord without the "Event_user" model? How can I manipulate the confirmed column in the User model?

I am using Rails 3.2.9

+4
source share
3 answers

User and Event are many-to-many , you cannot establish this relationship with only two models, you must have a join model or join a table.

In your case, you added the confirmed attribute, so you'll need a join model called Confirmation (as other people have recommended). Your definition associations will be:

 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 
+5
source

Instead of using for model User with relation

 has_and_belongs_to_many :events 

and change the Events_Users connection table (it's a little dirty)

it is better to use the Confirmation model with two relations belongs_of :

 belongs_to :user belongs_to :event 

Hope this helps you, Alessandro

+3
source

Since you have an additional field in the connection table, you will need a join model. Check this:

 class User has_many :invitations has_many :invited_events, -> {where(confirmed: false)}, class_name: 'Event', through: :invitations has_many :confirmed_events, -> {where(confirmed: true)}, class_name: 'Event', through: :invitations end class Event has_many :invitations has_many :invited_users, -> {where(confirmed: false)}, class_name: 'User', through: :invitations has_many :confirmed_users, -> {where(confirmed: true)}, class_name: 'User', through: :invitations end class Invitation belongs_to :user belongs_to :event end 

In this case, user.confirmed_events will provide user events only where the flag is set to true in the connection table.

0
source

All Articles