ruby-on-rails-3 – Rails:多级嵌套表单(接受嵌套属性)
发布时间:2020-12-17 02:40:45 所属栏目:百科 来源:网络整理
导读:我正在创建简单的博客级应用程序.以下是我的模特. class User ActiveRecord::Base attr_accessible :name,:posts_count,:posts_attributes,:comments_attributes has_many :posts has_many :comments accepts_nested_attributes_for :posts,:reject_if = pro
我正在创建简单的博客级应用程序.以下是我的模特.
class User < ActiveRecord::Base attr_accessible :name,:posts_count,:posts_attributes,:comments_attributes has_many :posts has_many :comments accepts_nested_attributes_for :posts,:reject_if => proc{|post| post['name'].blank?},:allow_destroy => true end class Post < ActiveRecord::Base attr_accessible :name,:user_id,:comments_attributes belongs_to :user has_many :comments accepts_nested_attributes_for :comments end class Comment < ActiveRecord::Base attr_accessible :content,:post_id,:user_id belongs_to :user belongs_to :post end 我试图通过使用rails的accepts_nested_attributes_for功能在一个表单中创建用户,发布和评论.下面是我的控制器和视图代码. 控制器———– class UsersController < ApplicationController def new @user = User.new @post = @user.posts.build @post.comments.build end def create @user = User.new(params[:user]) @user.save end end 形成 – – – – – <%= form_for @user do |f| %> <%= f.text_field :name %> <%= f.fields_for :posts do |users_post| %> <br>Post <%= users_post.text_field :name %> <%= users_post.fields_for :comments do |comment| %> <%= comment.text_field :content %> <% end %> <% end %> <%= f.submit %> <% end %> 使用上面的代码我成功地能够创建新用户,发布和评论,但问题是我无法将新创建的用户分配给新创建的评论.当我将新创建的评论检查到数据库中时,我得到了以下结果.我得到的user_id字段值为“nil”. #<Comment id: 4,user_id: nil,post_id: 14,content: "c",created_at: "2014-05-30 09:51:53",updated_at: "2014-05-30 09:51:53"> 所以我只想知道如何将新创建的评论分配给新创建的用户??? 谢谢, 解决方法
您必须明确指定user_id以获取评论!您在帖子下嵌套注释,因此注释将默认分配post_id,但是您在用户表单下间接嵌套注释,但在用户下没有直接嵌套注释,因此user_id在注释中保持空白.
尝试在Comment模型中创建回调后写入以设置user_id 在comment.rb after_create{|comment| comment.user_id = post.user_id comment.save } 希望这可以帮助 :) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |