ncarroll ncarroll - 7 months ago 34
Ruby Question

rails add record to has_many :through join table

class EventTeam < ActiveRecord::Base
belongs_to :event
belongs_to :team
end

class Event < ActiveRecord::Base
has_many :event_teams
has_many :teams, through: :event_teams
end

class Team < ActiveRecord::Base
has_many :event_teams
has_many :events, through: :event_teams
end


I am trying to add the :event_id and :team_id to the EventTeam join table when creating a new Event and can't seem to figure out how, despite an exhaustive search of similar questions such as: how to add records to has_many :through association in rails (I've tried all of these suggestions)

It seems that the following should work, though a NoMethodError is delivered: "undefined method `events' for #ActiveRecord::Relation []"

EventsController

def new
@event = Event.new(:team_id => params[:team_id])
end

def create
@team = Team.where(:id => params[:team_id])
@event = @team.events.create(event_params)
if @event.save
flash[:success] = "Event created!"
redirect_to @event
else
render 'new'
end
end


I have a similar situation in the same app with Users, Teams, and Memberships (join table). The following code automatically adds the :team_id and :user_id to the Memberships table when a user creates a new Team.

TeamsController

def new
@team = Team.new(:user_id => params[:user_id])
end

def create
@team = current_user.teams.create(team_params)
if @team.save
flash[:success] = "Team created!"
redirect_to @team
else
render 'new'
end
end


Any suggestions on how to accomplish this?

Answer

undefined method `events' for #ActiveRecord::Relation []

where returns an AR relation not a single instance, so @team.events won't work. Use find instead

@team = Team.find(params[:team_id])
@event = @team.events.create(event_params)

Update

could not find Team with 'id'=

You are getting team_id inside event hash, so params[:team_id] won't work. You need to use params[:event][:team_id]

@team = Team.find(params[:event][:team_id])
@event = @team.events.create(event_params)