【发布时间】:2013-11-06 03:46:01
【问题描述】:
我需要一些关于 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
后控制器
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 操作中的表单
<%= 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 标题。
调试参数
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"
我的问题与如何解决这个问题有关:
- 不知道是不是一定要在
post_params强参数方法中加上:category_attributes? - 日志和调试参数是否应该显示
Category属性 是否嵌套在Post参数中? - 在
Category散列参数中有一个空白的button键不在我的fields_for中使用表单助手时我是否遗漏了什么? - 是因为创建操作没有采取
build_category方法,我需要将其添加到创建 行动? - 将在
Category模型 (presence: true) 上进行验证 在Post表单上自动使用?
提前致谢。
更新:category_fields 在 fields_for 块内丢失。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 form-for actioncontroller strong-parameters