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?
@micropostand@commentbefore this form ? - mohameddiaa27render 'shared/_comment_form', micropost: @micropost. In your view change the global@micropostto localmicropost. - Justin