【发布时间】:2014-05-30 10:11:18
【问题描述】:
我正在创建简单的博客级应用程序。以下是我的模型。
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">
所以我只想知道如何将新创建的评论分配给新创建的用户???
谢谢,
【问题讨论】:
标签: ruby-on-rails-3 nested-forms fields-for