我有兩個使用has_and_belongs_to_many
的多對多關係模型。像這樣:如何使用has_and_belongs_to_many將新模型與現有模型相關聯
class Competition < ActiveRecord::Base
has_and_belongs_to_many :teams
accepts_nested_attributes_for :teams
end
class Team < ActiveRecord::Base
has_and_belongs_to_many :competitions
accepts_nested_attributes_for :competitions
end
如果我們假設我已經在數據庫中創建一些比賽,當我創建一個新的團隊,我想用一個嵌套的形式向新的團隊與任何有關比賽相關聯。
在這一點上,我真的需要幫助(已經堅持了幾個小時!),我認爲我現有的代碼已經走錯了方向,但我會顯示它以防萬一:
class TeamsController < ApplicationController
def new
@team = Team.new
@competitions.all
@competitions.size.times {@team.competitions.build}
end
def create
@team = Team.new params[:team]
if @team.save
# .. usual if logic on save
end
end
end
而這個觀點......這是我真正被困住的地方,所以我不會同時發佈我的努力。我希望每個比賽都有一個複選框列表,以便用戶可以選擇哪些比賽是合適的,而不選中那些不合適的比賽。
我真的堅持了這一個,這樣欣賞在正確的方向指向任何可以提供:)
謝謝你的回答(和apolgies需要幾天的迴應)。你的解決方案運行良好,儘管我花了一點時間來研究如何構建表單。 爲了其他人的利益,儘管團隊形式是使用form_for helper生成的,但對於比賽部分,我手動創建瞭如下複選框: <%= check_box_tag「team [competitions] []」,比賽。 id,@ team.competitions.include?(競賽),:id =>「team_competitions _#{competition.id}」%> – aaronrussell 2010-01-23 15:46:56