0
votes

I am trying to create comments that are associated with posts. There are 3 models User, microposts and Comments. Here are the associations that I have:
Comment Model

class Comment < ActiveRecord::Base
  belongs_to :user 
  belongs_to :micropost

  validates :user_id, presence: true
  validates :micropost_id, presence: true
end

Microposts Model

belongs_to :user
  has_many :comments, dependent: :destroy

User Model

has_many :microposts, dependent: :destroy
  has_many :comments

I have nested the route as:

resources :microposts do 
    resources :comments
  end

Here is my comment controller:

class CommentsController < ApplicationController

  def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = @micropost.comments.build(params[:comment])
    if @comment.save
      flash[:success] = "Comment created"
      redirect_to current_user
    else
      render 'shared/_comment_form'
    end
  end
end

Comment Form:

<%= form_for([@micropost, @comment]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Write your message.." %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

When I run this I get a form I get an argument error,
First argument in form cannot contain nil or be empty
I am wondering how do I solve this issue? If I just write micropost, @comment it seems to not recognize it either and I get an undefined local variable error. Why is the comment form not realizing that the micropost is from the comments controller to find the micropost_id?

1
do yo you set the values of @micropost and @comment before this form ? - mohameddiaa27
render 'shared/_comment_form', micropost: @micropost. In your view change the global @micropost to local micropost. - Justin
I have done the micropost: @micropost but it still doesn't seem to be working Justin. I will get a undefined local local variable or name error... - Jason
mohammed, i have set the values of micropost in the comments controller as you can see as well as in the user controller which is @comment = comment.new - Jason
@Jason where is this form ? what is the file ? - mohameddiaa27

1 Answers

1
votes

Lets first understand how this form works.

If your resource has associations defined, for example, you want to add comments to the micropost given that the routes are set correctly:

<%= form_for([@micropost, @comment]) do |f| %>
 ...
<% end %>

Where @micropost and @comment are defined before rendering the form.

example: @micropost = Micropost.find(params[:id]) and @comment = Comment.new

Later when you submit this form (only on that step) your create action is touched from your comments controller.

so basically what you need to do, is define the @micropost and @comment before calling the form_for