【发布时间】:2021-10-06 08:16:15
【问题描述】:
我有两个模型:游戏和作业。当我创建一个游戏时,我想自动创建一个与该游戏一起使用的作业,从而建立两者之间的关联。在我的游戏控制器中,我有:
def create
@game = Game.new(game_params)
@assignment = Assignment.new(assignment_params)
respond_to do |format|
if @game.save
format.html { redirect_to @game, notice: "Game was successfully created." }
format.json { render :show, status: :created, location: @game }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @game.errors, status: :unprocessable_entity }
end
end
end
private
def game_params
params.require(:game).permit(:home_team, :away_team)
end
def assignment_params
params.require(:assignment).permit(@game.game_id)
end
end
创建游戏时如何将 game_id 传递给分配参数?我的模型如下以防需要。我的分配模型中有一个game_id 列。
class Game < ApplicationRecord
has_one :assignment, dependent: :destroy
has_many :users, through: :assignments
end
class Assignment < ApplicationRecord
belongs_to :game
belongs_to :center_referee, class_name: 'User', foreign_key: "user_id"
belongs_to :assistant_referee_1, class_name: 'User', foreign_key: "user_id"
belongs_to :assistant_referee_2, class_name: 'User', foreign_key: "user_id"
end
游戏形式
<%= simple_form_for(@game) do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.input :home_team %>
<%= f.input :away_team %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
游戏控制器
def new
@game = Game.new
end
# POST /games or /games.json
def create
@game = Game.new(game_params)
respond_to do |format|
if @game.save
format.html { redirect_to @game, notice: "Game was successfully created." }
format.json { render :show, status: :created, location: @game }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @game.errors, status: :unprocessable_entity }
end
end
end
【问题讨论】:
-
如果你总是在游戏中创建任务,你可以在游戏模型中进行,不需要给控制器增加负担。查看嵌套属性。
-
你的表单是什么样子的?
-
上面添加了游戏表格。我已将 create_assignment 移至 Game 模型
标签: ruby-on-rails model controller associations