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
如何做到這一點有什麼建議?
出於某種原因,我得到錯誤「無法與‘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