ruby-on-rails – Rails 4 has_one协会形式没有建立
我需要一些关于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#新的动作 <%= 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表单提交时不保存类别标题. 调试参数 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? 提前致谢. 更新:在fields_for块中缺少category_fields. 解决方法
问题1:是的,您需要在post_params强参数方法中添加:category_attributes,如下所示:
def post_params params.require(:post).permit(:body,category_attributes: [:title]) end 问题#2:是的,这些参数应该是嵌套的,这是你的视图中的一个打字错误,因为你没有在父窗体构建器的范围内应用fields_for(复数形式),你也没有使用category_fields窗体构建器里面的fields_for块 视图应如下所示: <%= 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:是的,也运行子模型的验证,如果子进程的验证失败,父进程也会有错误,不会保存到数据库中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |