2013-09-10 17 views
2

這是我在Rails 4中的第一個應用,但我不確定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中。

信息

由於這是導軌4,以白名單的所有參數(在這個階段的發展至少),我已經使用許可!在made_gamesmade_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 %> 

我也應該注意到make_game有一種形式,made_game_instance是單獨的形式,而不是嵌套形式,所以我不相信s是accept_nested_attributes_for或fields_for的問題。

+1

'params'說'new_word1'而不是'new_word'。 – MurifoX

+0

謝謝你指出。這是我的帖子中的一個錯字。我只是在模式中確認表中的列確實被稱爲'new_word1'。我將相應地編輯OP。 – keb

+0

你可以發佈你的made_games控制器嗎? – Ivan

回答

2

在你made_games_instance_controller.rb

這條線......

@made_game_instance = @made_game.made_game_instances.build(params[:made_game_instance_params]) 

實際上應該是...

@made_game_instance = @made_game.made_game_instances.build(made_game_instance_params) 

有一個帶符號鍵沒有PARAMS散列條目:made_game_instance_params

+0

謝謝,這正是問題所在! – keb