简体   繁体   中英

How to create join table record in Rails, has many: through relationship

Classes user and event have a has many: through relationship.

class User < ActiveRecord::Base
  has_many :user_events
  has_many :events, :through => :user_events
end

class Event < ActiveRecord::Base
  has_many :user_events
  has_many :users, :through => :user_events
end

In my event controller I'd like to create a record for User_events, which I do right now with the following:

def create
  @event = Event.new(event_params)
  @user = User.find(current_user.id)
  @user_events = User.user_events.create
  @user_events.user_id = @user.id
  @user_events.event_id = @event.id
end

This feels heavy though so I figure there's a better, more "Rails way" of doing it. What's the correct way?

def create
  @event = Event.new(event_params)
  if @event.save
    @event.users << current_user
    redirect_to event_path(@event)
  else
    render action: :new
  end
end
def create
  @event = Event.new(event_params)
  @event.users.add(User.find(current_user.id))
  @event.save # I guess that you want to save the relation
end

This depends on what params are bringing and how they are formatted. If it's a form submission and it's bringing a user_id, you should be able to just create the event

user = User.find(params[:user_id]) user.events << Event.new(params[:event])

If you'd like to add it to the current_user:

current_user.events << Event.new(params[:event])

As you see it all depends on how the params are being passed and where you're getting the user from.

Those are a few options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM