这是我在 Rails 4 中的第一个应用程序,但我不确定 Rails 4 是否是问题所在。
我有如下嵌套资源:
resources :made_games do
resources :made_game_instances
end
当我尝试保存一个新的时made_game_instance
,这就是日志中发生的事情:
Started POST "/made_games/11/made_game_instances" for 127.0.0.1 at 2013-09-10 12:03:55 -0700
Processing by MadeGameInstancesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jEN2syjftjRtf3DBnijtp7gNVUEFrI+HYTUs+HFgo5M=", "made_game_instance"=>{"new_word1"=>"bluesky"}, "commit"=>"Create Made game instance", "made_game_id"=>"11"}
MadeGame Load (122.7ms) SELECT "made_games".* FROM "made_games" WHERE "made_games"."id" = $1 LIMIT 1 [["id", "11"]]
(14.0ms) BEGIN
SQL (215.9ms) INSERT INTO "made_game_instances" ("created_at", "made_game_id", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", Tue, 10 Sep 2013 19:03:55 UTC +00:00], ["made_game_id", 11], ["updated_at", Tue, 10 Sep 2013 19:03:55 UTC +00:00]]
(5.7ms) COMMIT
Redirected to http://localhost:3000/made_games/11/made_game_instances/5
Completed 302 Found in 458ms (ActiveRecord: 358.3ms)
您可以看到 params 散列包含new_game_instance
属性:new_word1
被分配值“bluesky”的散列。我无法弄清楚为什么这个分配没有出现在创建新的“made_game_instances”对象时随后生成的 SQL 中。
附加信息
由于这是 Rails 4,为了将所有参数列入白名单(至少在开发的这个阶段),我使用了 permit!在 和 的控制器底部的 params 私有方法made_games
中made_game_instances
。
made_games
控制器:
class MadeGamesController < ApplicationController
def new
@made_game = MadeGame.new
end
def create
@made_game = MadeGame.new(made_game_params)
if @made_game.save
flash[:notice] = "Here you go!"
redirect_to @made_game
else
flash[:notice] = "Something about that didn't work, unfortunately."
render :action => new
end
end
def show
@made_game = MadeGame.find(params[:id])
end
private
def made_game_params
params.require(:made_game).permit!
end
end
这是 github 存储库的链接:https ://github.com/keb97/madlibs/tree/users_making
用于创建新的表单made_game_instance
是:
<%= simple_form_for [@made_game, @made_game_instance] do |f| %>
<p>
<%= f.input :new_word1, label: @made_game.word1.to_s %>
</p>
<%= f.button :submit %>
<% end %>
我还应该注意,made_game 有一个表单,made_game_instance 有一个单独的表单,而不是嵌套表单,所以我不认为这是accepts_nested_attributes_for 或fields_for 的问题。