I'm trying to develop a app in Ruby on Rails 4.0 (already used older versions of this incredible framework) and I having some troubles.
I installed the FriendlyID gem and I think everything is okay, but I'm receiving errors when I try to test my app.
If I go to http://0.0.0.0:3000/categories/1
, this works. But when I click in "edit" in this page, or just go to http://0.0.0.0:3000/categories/electronics
(that's the slugged name of category with ID 1), I receive the following error:
Couldn't find Category with id=electronics
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id]) #Here's pointed the error
end
Category Model:
class Category < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
# Validations
validates_uniqueness_of :name, :case_sensitive => false
end
Category Controller:
(generated by scaffold for test purposes)
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
# GET /categories
# GET /categories.json
def index
@categories = Category.all
end
# GET /categories/1
# GET /categories/1.json
def show
end
# GET /categories/new
def new
@category = Category.new
end
# GET /categories/1/edit
def edit
end
# POST /categories
# POST /categories.json
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render action: 'show', status: :created, location: @category }
else
format.html { render action: 'new' }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /categories/1
# PATCH/PUT /categories/1.json
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_category
@category = Category.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def category_params
params.require(:category).permit(:name)
end
end
Migration:##
(I added friendlyId after create the Category table, but I think is okay)
class AddColumnToCategory < ActiveRecord::Migration
def change
add_column :categories, :slug, :string
add_index :categories, :slug, unique: true
end
end
Routes:
resources :categories
Hope you can help me. What I'm doing wrong in Rails 4.0?