【发布时间】:2016-08-20 19:21:50
【问题描述】:
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 连接表中,但似乎无法弄清楚如何,尽管对类似问题进行了详尽的搜索,例如:how to add records to has_many :through association in rails (I'已经尝试了所有这些建议)
似乎以下内容应该有效,尽管传递了 NoMethodError:“#ActiveRecord::Relation [] 的未定义方法 `events'”
事件控制器
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_id 和 :user_id 添加到 Memberships 表中。
团队控制器
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
关于如何完成此任务的任何建议?
【问题讨论】:
标签: ruby-on-rails ruby jointable