Daniel Gomez Firmat
Daniel Gomez Firmat

Reputation: 43

Comments to Projects and Users

I'm just new to rails and I'm trying to put together a comment feature on my app. However I'm getting the now annoying

Couldn't find Project without an ID

Routes.rb

  resources :projects do
    resources :comments
  end

User model.

  has_many :projects, dependent: :destroy
  has_many :comments

Project model.

  belong_to :user
  has_many :comments , dependent: :destroy

Comments model.

  belongs_to :user
  belongs_to :project

Comments controller.

class CommentsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]

def create
   @project = Project.find(params[:project_id])
   @comment = @project.comments.build(comment_params)
   @comment.user_id = current_user.id
       if @comment.save
      flash[:success] = "Comment created!"
      redirect_to @project
    else
      flash.now[:danger] = "Sorry! your comment was not created"
    end
  end


 def destroy
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
end

end

Result

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+/UjIRKAjE+DAATW6eV48xjX+6WW6a/y7Q8DS+nLeCnM8nzwpdzW1FuGXtXVpCGFS0vPivvMi7jvus9IQcjLjA==", "comment"=>{"body"=>""}, "commit"=>"Comment"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
Completed 404 Not Found in 24ms (ActiveRecord: 1.3ms)



ActiveRecord::RecordNotFound (Couldn't find Project without an ID):

---- Update 1 -------

<%= form_for(@comment) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :body, placeholder: "Write here" %>
  </div>
  <%= f.submit "comment", class: "btn btn-primary" %>
<% end %>

Any ideas?

Upvotes: 0

Views: 42

Answers (2)

Daniel Gomez Firmat
Daniel Gomez Firmat

Reputation: 43

Thanks all for your posts below is the right solution

<%= form_for ([@project , @comment]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :body, placeholder: "Compose new micropost..." %>
  </div>
  <%= f.submit "Comment", class: "btn btn-primary" %>
<% end %>

Params

  def comment_params
    params.require(:comment).permit(:body,:project_id,:user_id)
end

Upvotes: 0

Emu
Emu

Reputation: 5905

I don't know what's written on your form_url. But, definitely it is missing the project_id. So, I suggest you to use the following code:

<%= form_for [@project, @comment] do |f| %>

It'll create a POST request in root/projects/2/comments

Upvotes: 1

Related Questions