2013-05-20 24 views
0

我有一個Userhas_many :recipes。我正在使用simple_form,並嘗試使用表單來創建新配方。很簡單,對吧?我查看了十幾個SO問題,並且我認爲我已經修復了所有問題,包括accepts_nested_attributes_for以及其他所有問題。Rails的SimpleForm與嵌套模型:提交重定向到父模型

現在,當我提交表單創建一個新的配方,它重定向我與有關用戶錯誤用戶編輯表單。這是相關的代碼。

class User < ActiveRecord::Base 
    ... 
    attr_accessible ..., :recipes_attributes 

    has_many :recipes 
    accepts_nested_attributes_for :recipes 
end 


class Recipe < ActiveRecord::Base 
    ... 
    belongs_to :user 

end 

而且recipes/new.html.haml

= simple_nested_form_for @user do |f| 

    = f.simple_fields_for :recipes, @user.recipes do |rf| 
    = rf.input :name 
    = rf.input :source 
    = rf.input :link 
    = rf.input :season, collection: %w(spring summer fall winter), prompt: 'Choose season', required: false 
    = rf.input :protein, as: :radio_buttons, required: false 
    = rf.input :course, collection: ['appeteizer', 'soup', 'dessert', 'entrée', 'side', 'salad'], prompt: 'Choose course', required: false 
    = rf.input :featured, as: :boolean, required: false 
    = rf.input :directions, as: :text 
    .actions 
     = f.submit 'Save' 
     or 
     = link_to 'Cancel', user_recipes_path(@user) 

我也試過= f.simple_fields_for :recipe do |rf|

而這裏的RecipesController

def new 
    @user = User.find(params[:user_id]) 
    @recipe = @user.recipes.build || @recipe.new 

    respond_to do |format| 
     format.html 
     format.json { render json: @recipe } 
    end 
    end 

new方法看起來像它試圖張貼到用戶的控制,而不是的食譜這就解釋了爲什麼它會將我重定向到編輯用戶。這裏的PUT請求的日誌:

Started PUT "https://stackoverflow.com/users/4" for 127.0.0.1 at 2013-05-19 22:31:07 -0700 
Processing by UsersController#update as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"QmCo025nqR9vJt49To1gQ7/edv4MSlvuwHYotEihI2E=", "user"=>{"recipes_attributes"=>{"0"=>{"name"=>"dffd", "source"=>"dfswer", "link"=>"ewrre", "season"=>"", "course"=>"", "featured"=>"0", "directions"=>"werew"}}}, "commit"=>"Save", "id"=>"4"} 

我知道這在技術上是一個form_for @user,但因爲它是創建一個配方,我怎麼會提出這樣的放去recipes創建一個新的配方?我希望它把recipes_attributesrecipe_attributes?這是爲了一個新的配方,我試圖讓它接受配方或食譜的嵌套屬性(我使這些形式相應匹配)。我想我也對此感到困惑。

回答

0

您已經創建了用戶simple_nested_form_for @user一種形式。這就是爲什麼表單被提交給users_controller。

如果你沒有在任何形式的用戶相關的領域,創造配方

form_for([@user, @recipe]) do 
+0

我已經試過了,但配方並沒有獲得與user_ID的提交表單。我只是將其添加爲隱藏字段? – nickcoxdotme

+0

更新了我的答案。這將提交帶有用戶標識的表單。 – 2013-05-20 06:22:20

+0

非常感謝。我正在失去理智! – nickcoxdotme