2016-04-26 94 views
0
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 

如何做到這一點有什麼建議?

回答

1

未定義的方法'事件[]

where返回AR關係沒有單個實例,所以@team.events將無法​​正常工作。使用find代替

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

更新

無法與 'ID' 找到團隊=

你得到team_idevent散,所以params[:team_id]將無法​​正常工作。您需要使用params[:event][:team_id]

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

出於某種原因,我得到錯誤「無法與‘ID’=我只是把PARAMS 1,而不是找隊[:TEAM_ID],創建事件,並記錄增加到連接表 - 所以.find而不是.where絕對有效。奇怪的是,我可以在new_event路徑的url中看到team_id = 1。 – ncarroll

+0

@ncarroll這個動作產生了什麼參數? – Pavan

+0

{ 「UTF8」=> 「✓」, 「authenticity_token」=> 「EryBDSRyQWO3zEXCjjz0J/Y9IOy0bfCw5tVhMnN + MiG0cOyJYWIWPNVihVbyP9C36raLXZ8B2uN8HR9PlCqTzg ==」, 「事件」=> { 「日期」=> 「2016年4月20日」, 「名「>」test「, 」location「=>」test「, 」venue「=>」test「, 」team_id「=>」1「}, 」commit「=>」Create event「} – ncarroll

0

只要指定關係的第一個值,因爲你是唯一索引與價值id搜索,所以這應該是很好:

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

這是因爲.where,不像find_byfind(1)返回Relation,不它的第一個值。

但是,在現代版本的導軌中,我看到建議使用的確實是where.first對,而不是find。對於#ActiveRecord ::關係