我正在創建一個應用程序,同時學習如何在Ruby中進行編碼。我正在製作一個簡單的聯盟應用程序,我可以創建新的球隊,球員,聯賽...#RubyOnRails多對多的關係沒有插入連接表
我有一個團隊模型和一個聯盟模型,因爲一個團隊可以進入多個聯盟和一個聯盟可以有不止一個團隊他們是多對多的協會。但是,當我創建/編輯一個團隊,它不會插入任何東西到連接表中,只會改變其他屬性。
的車型:
團隊模型
class Team < ActiveRecord::Base
validates_presence_of :name
has_many :teams_join_leagues, :dependent => :destroy
has_many :leagues, through: :teams_join_leagues
end
聯賽型號
class League < ActiveRecord::Base
validates_presence_of :name, :begindate, :enddate, :prizepool, :season_id
validate :start_must_be_before_end_time
has_many :teams_join_leagues, :dependent => :destroy
has_many :teams, through: :teams_join_leagues
加入TeamLeague型號
class TeamsJoinLeague < ActiveRecord::Base
belongs_to :team
belongs_to :league
end
TeamController PARAM功能:
def team_params
params.require(:team).permit(:name, leagues: [:id])
end
創建功能:
def create
@team = Team.new(team_params)
respond_to do |format|
if @team.save
format.html { redirect_to @team, notice: 'Team was successfully created.' }
format.json { render :show, status: :created, location: @team }
else
format.html { render :new }
format.json { render json: @team.errors, status: :unprocessable_entity }
end
end
end
什麼,我做錯了什麼?它從來沒有插在連接表什麼讓所有的球隊沒有聯賽:/
我相信這是在這裏回答:http://stackoverflow.com/questions/5218994/how-to-save-many-has-many-through-objects-at-the-same-time-in-rails Best –
@RandallValenciano我在創建函數時做了這些,但現在給我一個錯誤。 未定義的方法'每個」近親:NilClass 高清創建 @team = Team.new(team_params) @ team.leagues = @leagues team.save 感謝您的幫助:) – JoaoMorais