我需要一些关于Rails 4如何使用has_one和belongs_to关联的提示。
我的表单没有保存has_one关系
Post模型
class Post < ActiveRecord::Base
validates: :body, presence: true
has_one :category, dependent: :destroy
accepts_nested_attributes_for :category
end
class Category < ActiveRecord::Base
validates :title, presence: true
belongs_to :post
end后控制器
class PostController < ApplicationController
def new
@post = Post.new
@post.build_category
end
def create
@post = Post.new(post_params)
end
private
def post_params
params.require(:post).permit(:body)
end
end表单在Post#new action中
<%= form_for @post do |form| %>
<%= form.label :body %>
<%= form.text_area :body %>
<%= fields_for :category do |category_fields| %>
<%= category_fields.label :title %>
<%= category_fields.text_field :title %>
<% end %>
<%= form.button "Add Post" %>
<% end %>当Post表单提交时,它不会保存category标题。
Debug params
utf8: ✓
authenticity_token: 08/I6MsYjNUhzg4W+9SWuvXbSdN7WX2x6l2TmNwRl40=
post: !ruby/hash:ActionController::Parameters
body: 'The best ice cream sandwich ever'
category: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
title: 'Cold Treats'
button: ''
action: create
controller: posts应用程序日志
Processing by BusinessesController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"08/I6MsYjNUhzg4W+9SWuvXbSdN7WX2x6l2TmNwRl40=",
"post"=>{"body"=>"The best ice cream sandwich ever"},
"category"=>{"title"=>"Cold Treats", "button"=>""}在Rails控制台..。我可以成功地运行以下命令
> a = Post.new
=> #<Post id: nil, body: "">
> a.category
=> nil
> b = Post.new
=> #<Post id: nil, body: "">
> b.build_category
=> #<Post id: nil, title: nil>
> b.body = "The best ice cream sandwich ever"
=> "The best ice cream sandwich ever"
> b.category.title = "Cold Treats"
=> "Cold Treats"我要问的问题是如何处理这个问题:
:category_attributes强参数方法中添加post_params?Category属性嵌套在Post参数中?Category哈希参数中,有一个空白的button键,它不在我的fields_for中,我在使用表单助手时遗漏了什么吗?build_category方法,我需要将它添加到create操作中吗?Category模型(presence: true)上的验证会自动在Post表单上使用吗?提前谢谢。
更新:在category_fields块中缺少fields_for。
发布于 2013-11-06 04:06:53
问题1:是的,您需要在post_params强参数方法中添加:category_attributes,如下所示:
def post_params
params.require(:post).permit(:body, category_attributes: [:title])
end问题2:是的,参数应该是嵌套的,这是您的视图中的一个错误,因为您没有在父表单生成器的作用域中应用fields_for (顺便说一句复数),也没有在fields_for块中使用category_fields表单生成器!
视图应该如下所示:
<%= form_for @post do |form| %>
<%= form.label :body %>
<%= form.text_area :body %>
<%= form.fields_for :category do |category_fields| %>
<%= category_fields.label :title %>
<%= category_fields.text_field :title %>
<% end %>
<%= form.button "Add Post" %>
<% end %>问题#3:按钮参数可能在错误的位置,因为在您的视图中混合了表单构建。
问题#4:如果接受嵌套属性,则不需要在创建操作中构建子模型。
问题5:是的,子模型的验证也会运行,如果子模型验证失败,父服务器也会出现错误,并且不会保存到数据库中。
发布于 2013-11-06 07:42:29
@雪橇你说得对。但对于未来的Rails 4.1,粗体(**)将被废弃。
def post_params
params.require(:post).permit **(:body, :category_attributes => [:title])**
end粗体将被迫如此(:body,category_attributes::title)
https://stackoverflow.com/questions/19803711
复制相似问题