Search code examples
ruby-on-railsruby-on-rails-4activerecordrails-activerecordfriendly-id

Not able to find an object by slug using frindly_id Couldn't find Article without an ID


I'm Like you see I'm simply trying to have comments on each article show page also I'm using Friendly_id. The issue is that I'm not able to find the article by using its slug from the Comments controller and I'm not sure where the issue is.

Comments controller

 class CommentsController < ApplicationController

  def create
    @article = Article.friendly.find(params[:slug])
    @comment = @article.comments.create(comments_params)
    redirect_to @article_path(@article)
  end

private

  def comments_params
    params.require(:comment).permit(:name, :body)
  end
end

Article Controller

class ArticlesController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]



def index
    @Articles = Article.all
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
      if @article.save
        redirect_to @article
      else
        render 'new'
      end
    end

    def show
      find_article
    end

    def edit
      find_article
    end

    def update
      @article = Article.find_by_slug(params[:id])
      if @article.update(article_params)
        redirect_to @article
      else
        render 'edit'
      end
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to root_path
    end

    private

    def find_article
      @article = Article.friendly.find(params[:id])
    end

    def article_params
      params.require(:article).permit(:title, :content, :slug)
    end
  end

comment form

<%= form_for ([@article, @article.comments.build]) do |f| %>
  <%= f.label :Name %>
  <%= f.text_field :Name %>
<br>
  <%= f.label :Body %>
  <%= f.text_area :Body %>
<br>
  <%= f.submit %>
<% end %>

comment

<p><%= comment.content %><p/>

Article Model

class Article < ActiveRecord::Base
  has_many :comments
  extend FriendlyId
  friendly_id :title, use: [:slugged, :finders]
end

Comment Model

class Comment < ActiveRecord::Base
  belongs_to :article
end

Routes

Rails.application.routes.draw do devise_for :users root 'articles#index' resources :articles do resources :comments end end

Solution

  • I guess it should be like this:

    class CommentsController < ApplicationController
    
      def create
        @article = Article.friendly.find(params[:article_id])
        @comment = @article.comments.create(comments_params)
        redirect_to article_path(@article)
      end
    
    private
    
      def comments_params
        params.require(:comment).permit(:name, :body)
      end
    end