Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 408
Sanjay Salunkhe Avatar asked May 30 '14 10:05

Sanjay Salunkhe


Video Answer


1 Answers

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 :)

like image 199
Himesh Avatar answered Oct 20 '22 01:10

Himesh