我有三个模型“事件”,“团队”和“用户”与各种ActiveRecord关联,我在创建新的事件对象并将其与team_id相关联时遇到问题。也许我错过了关系的一些东西。它们的定义如下:
class User < ActiveRecord::Base
has_many :teams
has_many :events, through: :teams
end
class Team < ActiveRecord::Base
has_many :events
has_many :users
end
class Event < ActiveRecord::Base
belongs_to :team
has_many :users, through: :teams
end
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
@event = current_team.events.build(event_params)
if @event.save
flash[:success] = "Event created!"
redirect_to @event
else
render 'new'
end
end
class TeamsController < ApplicationController
def new
@team = Team.new
end
def create
@team = current_user.teams.build(team_params)
if @team.save
flash[:success] = "Team created!"
redirect_to @team
else
render 'new'
end
end
当我提交create new事件表单时,在事件控制器中触发错误,因为无法识别current_team.events。我对RoR比较新,所以任何帮助都会非常感激!
答案 0 :(得分:0)
从您的代码中,似乎current_team
中未定义EventsController
。如果您从表单中获得团队ID,则可以执行以下操作:
current_team = Team.find(params[:team_id])
然后它应该有用。
答案 1 :(得分:0)
用户和团队之间是否有联接表?从这个例子中你可以看出这两个模型之间的多对多关系,但我没有看到定义的关系。查看Rails guides
答案 2 :(得分:0)
在团队模型中,您应该像连接表一样执行以下操作
class Team < ActiveRecord::Base
belongs_to :event
belongs_to :user
end
在活动模型中:
class Event < ActiveRecord::Base
has_many :teams
has_many :users, through: :teams
end
我仍然不知道你真正想要的是什么,如果Team表是一个联接表,你想让它像一个表,那么这应该没关系,但我建议你再次检查你的关系检查导轨指南以完全理解你在这里要做的事情