rails 添加记录到 has_many :through join table

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

我试图在创建新事件时将 :event_id 和 :team_id 添加到 EventTeam 加入 table,但似乎无法弄清楚如何,尽管详尽搜索类似问题,例如:how to add records to has_many :through association in rails(我已经尝试了所有这些建议)

尽管传递了 NoMethodError,但似乎以下应该有效:"undefined method `events' for #ActiveRecord::Relation []"

事件控制器

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

我在与用户、团队和会员资格相同的应用程序中遇到了类似的情况(加入 table)。当用户创建新团队时,以下代码会自动将 :team_id 和 :user_id 添加到 Memberships table。

团队控制器

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

关于如何完成此任务有什么建议吗?

只需指定关系的第一个值,因为您是通过具有值 id 的唯一索引进行搜索的,所以这样应该很好:

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

那是因为 .where,不像 find_byfind(1) 返回一个 Relation,而不是其中的第一个值。

但是,在 rails 的现代版本中,我看到建议使用完全 where.first 对,而不是 find

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

where returns AR 关系 不是 单个实例 ,因此 @team.events 将不起作用。使用 find 代替

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

更新

could not find Team with 'id'=

您在 event 哈希中得到 team_id,因此 params[:team_id] 将不起作用。您需要使用 params[:event][:team_id]

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