我正在学习如何在Ruby中编写代码来创建应用程序。我正在创建一个简单的联盟应用程序,我可以创建新的团队,球员,联赛......
我有一个团队模型和一个联盟模式,因为一个团队可以进入多个联盟,一个联盟可以拥有多个团队,他们是多对多的联盟。但是,当我创建/编辑团队时,它不会在连接表中插入任何内容,只会更改其他属性。
模特:
团队模型
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
我做错了什么?它永远不会在联接表上插入任何东西,让所有团队都没有联赛:/
答案 0 :(得分:0)
我假设你的teams_join_leagues表是这样的:
create_table "teams_join_leagues", force: :cascade do |t|
t.integer "team_id"
t.integer "league_id"
....
end
所以在您的创建团队中,它应该看起来像这样或类似的
def create
@league = current_team.teams_join_leagues.build(league_id: params[:league_id])
if @league.save
....
end