0

我有User一个has_many :recipes。我正在使用simple_form,并尝试使用表单来创建新食谱。很简单,对吧?我已经浏览了十几个 SO 问题,我认为我已经解决了所有问题,包括accepts_nested_attributes_for所有问题。

现在,当我提交表单以创建新配方时,它会将我重定向到用户编辑表单,其中包含有关用户的错误。这是相关的代码。

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|

这是new方法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

看起来它正在尝试发布到用户控制器而不是食谱控制器,这解释了为什么它将我重定向到编辑用户。这是 put 请求的日志:

Started PUT "/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"}

我知道它在技术上是 a form_for @user,但既然它正在创建一个食谱,我将如何让那个 put 去recipes创建一个新的食谱?我希望它放recipes_attributes,还是recipe_attributes?这是一个新的食谱,我试着让它接受一个或多个食谱的嵌套属性(我使表格相应地匹配)。我想我也对此感到困惑。

4

1 回答 1

0

您已经为 User 创建了一个表单simple_nested_form_for @user。这就是表单被提交给 users_controller 的原因。

如果表单中没有任何与用户相关的字段,请为食谱创建一个表单

form_for([@user, @recipe]) do
于 2013-05-20T05:44:47.303 回答