Rails:多层嵌套表单(接受嵌套属性) [英] Rails: multi level nested Forms (accepts nested attributes)
问题描述
我正在创建简单的博客级应用程序.下面是我的模型.
I am creating simple blog level application. below are my models.
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
功能以一种形式创建用户,发布和评论.下面是我的控制器和查看代码.
I am trying to create user,post and comment in one form by using accepts_nested_attributes_for
feature of rails. Below is my controller and view code.
控制器-----------
Controller-----------
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----------
<%= 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".
With the above code i am successfully able to create new user,post and comment but the problem is that i am not able to assign newly created user to newly created comment.when i checked the newly created comment into the database i got below result.I am getting user_id field value of "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">
所以我只想知道我们如何将新创建的注释分配给新创建的用户?
So I just want to know how we can assign newly created comment to newly created user???
谢谢
推荐答案
您将必须显式分配user_id进行注释!您是在帖子下嵌套评论,因此默认情况下将为评论分配post_id,但是尽管您是在用户表单下间接嵌套评论,但用户下没有直接嵌套评论,因此user_id在评论中保持空白.
You will have to explicitly assign user_id for comments! You are nesting comments under posts, so comments would be having post_id assigned by default but though you are nesting comments under user form indirectly, there is no direct nesting of comments under user, so user_id remains blank in comments.
在注释模型中创建回调以设置user_id后尝试编写
Try writing after create callback in Comment model to set user_id
在comment.rb
In comment.rb
after_create{|comment|
comment.user_id = post.user_id
comment.save
}
希望这会有所帮助:)
这篇关于Rails:多层嵌套表单(接受嵌套属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!