Search code examples
ruby-on-railsmodelcontroller

Find category within category model - Rails


When a category is deleted, contents/posts with same category_id also needs be destroyed.

Here is my categories controller.

#Categories Controller

def destroy
    authorize @category
    @category.destroy
    respond_to do |format|
      format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_category
      @category = Category.find(params[:id])
    end

    def category_params
      params.require(:category).permit(:title, :user_id, :image)
    end

Inside my Category model, I have added a after_destory.

#Category model
    
      after_destroy :remove_content

  private

  def remove_content
    if Content.exists?(:category_id => self.id)
      Content.destroy(the_content)
    end
  end


  def the_content
    @the_content = Content.where(category_id: self.id)
  end

I use self.id to grab category_id, but the category uses id and title as uri.

  def to_param
    "#{id} #{title}".parameterize
  end

Content belongs to category.

#Content model
class Content < ActiveRecord::Base
  has_attached_file :image, styles: { medium: "300x160#", thumb: "100x53#" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

  belongs_to :user
  belongs_to :category

  def to_param
    "#{id} #{title}".parameterize
  end

end

How can I grab category_id from CategoriesController without self.id ?


Solution

  • Just use association for this:

    classs Category < ActiveReocrd::Base
    
      has_many :contents, dependent: :destroy
    

    dependend: :destroy does exactly what you are trying to achieve. It adds a hook destroying all the contents which belongs to deleted category. Note, do not use @category.delete as it is not triggering any hooks - always use @category.destroy