Rails: multi-level nested forms (accepts nested attributes)

I am creating a 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 a user, message and comment in one form using accepts_nested_attributes_forthe rails function. 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

The 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 can successfully create a new user, post and comment, but the problem is that I cannot assign a newly created user to a newly created comment. When I checked the newly created comment in the database I received below result.I gets the value of the user_id field "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 a newly created comment to a newly created user.

Thank,

+4
1

user_id ! , post_id, , , , user_id .

user_id

comment.rb

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

, :)

+5

Source: https://habr.com/ru/post/1542634/


All Articles