Join tables and rails

I have events and users / teams.

class Event
  has_many :users, :through => :registrations
end
class User
  has_many :events, :through => :registrations
end
class Registration
  belongs_to :users
  belongs_to :events
end

When I register a user, I connect it to the event as follows:

@event.users << @user

Does it implicitly create a registration object for the user / event? I set the: goal_amount column in my registration transfer, and I would like to be able to set: goal_amount when creating the registration. I need to explicitly create a registration (i.e.: Registration.create(:user_id => @user.id, :event_id => @event.id, :goal_amount => params[:goal_amount])to make this happen?

+3
source share
1 answer

Yes, adding a user to an event automatically creates a relationship object.
And yes, you must manually create the relation if you want to add this parameter to the middle table.

, , add_user .

def add_user user, goal_amount
    Registration.create({
        :user => user,
        :event => self,
        :goal_amount => goal_amount)
    })
end

@event.add_user @user, 100
+2

Source: https://habr.com/ru/post/1757286/


All Articles