我需要一些关于 Rails 4 如何与 has_one 和belongs_to 关联工作的指针。
我的表单没有保存 has_one
关系
岗位模型
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
后 Controller
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 %>
它没有保存
category
提交 Post 表单时的标题。调试参数
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
hash 参数有一个空白button
不在我的 key 中 fields_for
使用表单助手时我错过了什么吗? build_category
方法,我需要将此添加到创建行动?
Category
上进行验证模型 ( presence: true
) 是自动用于
Post
形式? 提前致谢。
更新:失踪
category_fields
内fields_for
堵塞。
最佳答案
问题 #1:是的,您需要添加 :category_attributes
在 post_params
像这样的强参数方法:
def post_params
params.require(:post).permit(:body, category_attributes: [:title])
end
问题#2:是的,参数应该是嵌套的,这是您 View 中的一个错字,因为您没有应用
fields_for
(顺便说一下)在父表单构建器的范围内,您也没有使用 category_fields
fields_for
内的表单生成器堵塞!View 应如下所示:
<%= 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:由于 View 中的混合表单构建,按钮参数可能位于错误的位置。
问题#4:如果您接受嵌套属性,则无需在创建操作中构建子模型
问题 #5:是的,子模型的验证也会运行,如果子模型的验证失败,父模型也会出错并且不会保存到数据库中。
关于ruby-on-rails - Rails 4 has_one 关联表单未构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803711/