轨添加记录的has_many:通过连接表
问题描述:
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
我试图加入:事项标识和:TEAM_ID到EventTeam创建一个新的事件时,连接表,似乎无法弄清楚如何,尽管穷举搜索类似的问题,如:how to add records to has_many :through association in rails(我试过所有这些建议)轨添加记录的has_many:通过连接表
似乎下面应该工作,虽然一个NoMethodError传递:“未定义的方法`事件'为#ActiveRecord ::关系[]”
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
我在与用户,团队和成员资格(连接表)相同的应用程序中也有类似的情况。当用户创建新的Team时,以下代码会自动将:team_id和:user_id添加到成员资格表中。
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
如何做到这一点有什么建议?
答
未定义的方法'事件[]
where
返回AR关系没有单个实例,所以@team.events
将无法正常工作。使用find
代替
@team = Team.find(params[:team_id])
@event = @team.events.create(event_params)
更新
无法与 'ID' 找到团队=
你得到team_id
内event
散,所以params[:team_id]
将无法正常工作。您需要使用params[:event][:team_id]
@team = Team.find(params[:event][:team_id])
@event = @team.events.create(event_params)
答
只要指定关系的第一个值,因为你是唯一索引与价值id
搜索,所以这应该是很好:
@team = Team.where(id: params[:team_id]).first
@event = @team.events.create(event_params)
这是因为.where
,不像find_by
或find(1)
返回Relation
,不它的第一个值。
但是,在现代版本的导轨中,我看到建议使用的确实是where.first
对,而不是find
。对于#ActiveRecord ::关系
出于某种原因,我得到错误“无法与‘ID’=我只是把PARAMS 1,而不是找队[:TEAM_ID],创建事件,并记录增加到连接表 - 所以.find而不是.where绝对有效。奇怪的是,我可以在new_event路径的url中看到team_id = 1。 – ncarroll
@ncarroll这个动作产生了什么参数? – Pavan
{ “UTF8”=> “✓”, “authenticity_token”=> “EryBDSRyQWO3zEXCjjz0J/Y9IOy0bfCw5tVhMnN + MiG0cOyJYWIWPNVihVbyP9C36raLXZ8B2uN8HR9PlCqTzg ==”, “事件”=> { “日期”=> “2016年4月20日”, “名“>”test“, ”location“=>”test“, ”venue“=>”test“, ”team_id“=>”1“}, ”commit“=>”Create event“} – ncarroll