我有一个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"}
我知道它在技术上是form_for @user
,但由于它正在创建一个配方,我该如何将它放到recipes
创建一个新配方?我是否希望它放置recipes_attributes
或recipe_attributes
?这是一个新的食谱,我尝试让它接受配方或食谱的嵌套属性(我使表格相应地匹配)。我想我也很困惑。
答案 0 :(得分:0)
您已为用户simple_nested_form_for @user
创建了一个表单。这就是为什么表单被提交给users_controller。
如果表单中没有任何与用户相关的字段,请为食谱创建表单
form_for([@user, @recipe]) do