开发者

Joins Tables & Rails

开发者 https://www.devze.com 2023-01-10 00:57 出处:网络
I have events and users/teams. class Event has_many :users, :through => :registrations end class User has_many :events, :through => :registrations

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'm connecting them to the event like so:

@event.users << @user

Does this implicitly create the Registration object for the user/event? I've put a :goal_amount column in my Registration migration, and I would like to be able to set the :goal_amount when the Registration is created. Do I need to explicitly create a Registration (ie: Registration.create(:user_id => @user.id, :event_id => @event.id, :goal_amount => params[:goal_amoun开发者_如何学Got]) to make this happen?


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

One solution to make it look cooler would be to create a add_user method in the event object.

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

Then you just have to call

@event.add_user @user, 100
0

精彩评论

暂无评论...
验证码 换一张
取 消