【问题标题】:Rails: multi level nested Forms (accepts nested attributes)Rails:多级嵌套表单(接受嵌套属性)
【发布时间】: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


    【解决方案1】:

    您必须为 cmets 显式分配 user_id!您将 cmets 嵌套在帖子下,因此 cmets 将默认分配 post_id,但尽管您将 cmets 间接嵌套在用户表单下,但用户下没有直接嵌套 cmets,因此 user_id 在 cmets 中保持空白。

    在 Comment 模型中创建回调后尝试编写设置 user_id

    在comment.rb中

    after_create{|comment|
      comment.user_id = post.user_id
      comment.save
    }
    

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2022-11-15
      相关资源
      最近更新 更多