Rails: multi level nested Forms (accepts nested attributes)

旧城冷巷雨未停 提交于 2019-11-30 05:43:27

问题


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

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 %>

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???

Thanks,


回答1:


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.

Try writing after create callback in Comment model to set user_id

In comment.rb

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

Hope this helps :)



来源:https://stackoverflow.com/questions/23952099/rails-multi-level-nested-forms-accepts-nested-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!