FriendlyId重定向到篮子或更正链接

时间:2017-04-10 13:11:04

标签: ruby-on-rails ruby friendly-id

我刚刚安装了FriendlyID来更改我网站的网址。 我已经为类别设置了这个,虽然链接会在我点击它们时更改为basket/(correct-product)时更改。

这真的很烦人,我已经通过下面的代码并删除了所有的篮子引用,它仍然发生。 谁能指出我正确的方向?

Category.rb

class Category < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: [:slugged, :history]
  has_many :products
end

这是在控制台中运行的代码:

Started GET "/categories/log-stores" for 88.97.48.111 at 2017-04-10 13:03:11 +0000
Cannot render console from 88.97.48.111! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by CategoriesController#show as HTML
  Parameters: {"id"=>"log-stores"}
  Category Load (0.2ms)  SELECT  `categories`.* FROM `categories` WHERE `categories`.`id` = 0 LIMIT 1
Redirected to https://market2-walsh259.c9users.io/baskets/log-stores
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)


Started GET "/baskets/log-stores" for 88.97.48.111 at 2017-04-10 13:03:11 +0000
Cannot render console from 88.97.48.111! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by BasketsController#show as HTML
  Parameters: {"id"=>"log-stores"}
  Basket Load (0.2ms)  SELECT  `baskets`.* FROM `baskets` WHERE `baskets`.`id` = 0 LIMIT 1
Redirected to https://market2-walsh259.c9users.io/baskets/log-stores
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)


Started GET "/baskets/log-stores" for 88.97.48.111 at 2017-04-10 13:03:11 +0000
Cannot render console from 88.97.48.111! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by BasketsController#show as HTML
  Parameters: {"id"=>"log-stores"}
  Basket Load (0.2ms)  SELECT  `baskets`.* FROM `baskets` WHERE `baskets`.`id` = 0 LIMIT 1
Redirected to https://market2-walsh259.c9users.io/baskets/log-stores
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)


Started GET "/baskets/log-stores" for 88.97.48.111 at 2017-04-10 13:03:11 +0000
Cannot render console from 88.97.48.111! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by BasketsController#show as HTML
  Parameters: {"id"=>"log-stores"}
  Basket Load (0.2ms)  SELECT  `baskets`.* FROM `baskets` WHERE `baskets`.`id` = 0 LIMIT 1
Redirected to https://market2-walsh259.c9users.io/baskets/log-stores
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)

我的categories_controller.rb

class CategoriesController < ApplicationController
  before_action :set_category, only: [:show, :edit, :update, :destroy]
   before_action :set_basket, only: [:show, :destroy]
  rescue_from ActiveRecord::RecordNotFound, with: :invalid_basket

  # GET /categories
  # GET /categories.json
  def index
    @categories = Category.all
    @top_ups = @categories [8]
    @log_stores = @categories [6]
    @smokeless_coal = @categories [5]
    @log_packages = @categories [4]
    @seasoned_logs = @categories [3]
    @kiln_dried_hardwood_logs = @categories [1]
    @logs_for_pizza_ovens = @categories [2]
    @logs_for_firepits = @categories [9]
  end

  # GET /categories/1
  # GET /categories/1.json
  def show
    @products = Product.where(category_id: params[:id])
    if request.path != category_path(@category)
      redirect_to @category, status: :moved_permanently
    end
  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 :show, status: :created, location: @category }
      else
        format.html { render :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 { render :show, status: :ok, location: @category }
      else
        format.html { render :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, notice: 'Category was successfully destroyed.' }
      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(:title, :description)
    end
     def set_basket
        @basket = Basket.find(params[:id])
    end

    def basket_params
        params[:basket]
    end

    def invalid_basket
        logger_error = 'Your trying to access an invalid basket'
        redirect_to basket_url, notice: 'Invalid basket'
    end
end

Baskets_controller.rb

class BasketsController < ApplicationController

    before_action :set_basket, only: [:show, :destroy]
    rescue_from ActiveRecord::RecordNotFound, with: :invalid_basket

    def new
        @basket = Basket.new
    end


    def show
         @basket = Basket.find(params[:id])
    end
    def index
        @basket = Basket.find(params[:id])
    end


    def destroy
        @basket.destroy if @basket.id == session[:basket_id]
        session[:basket_id] = nil
        redirect_to home_url, notice: 'Your basket is empty'
    end

    private

    def set_basket
        @basket = Basket.find(params[:id])
    end

    def basket_params
        params[:basket]
    end

    def invalid_basket
        logger_error = 'Your trying to access an invalid basket'
        redirect_to basket_url, notice: 'Invalid basket'
    end
end

Basket.rb

class Basket < ActiveRecord::Base
  has_many :product_items, dependent: :destroy

  def add_product(product_id)
      current_item = product_items.find_by(product_id: product_id)
      if current_item
          current_item.quantity += 1
      else
          current_item = product_items.build(product_id: product_id)
      end
      current_item
  end

  def total_price
       product_items.to_a.sum{|item| item.total_price}
  end
end

Application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  before_action :set_basket, only: [:show, :destroy]
  protect_from_forgery with: :exception



  def set_basket
    @basket = Basket.find(params[:id])
  end
  private
  def basket_params
      params[:basket]
  end

  def invalid_basket
      logger_error = 'Your trying to access an invalid basket'
      redirect_to basket_url, notice: 'Invalid basket'
  end
end

数据库具有以下内容:

create_table "categories", force: :cascade do |t|
  t.string "title",       limit: 255
  t.text   "description", limit: 65535
  t.string "slug",        limit: 255
end

add_index "categories", ["slug"], name: "index_categories_on_slug", using: :btree

create_table "friendly_id_slugs", force: :cascade do |t|
  t.string   "slug",           limit: 255, null: false
  t.integer  "sluggable_id",   limit: 4,   null: false
  t.string   "sluggable_type", limit: 50
  t.string   "scope",          limit: 255
  t.datetime "created_at"
end

add_index "friendly_id_slugs", ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true, using: :btree
add_index "friendly_id_slugs", ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type", using: :btree
add_index "friendly_id_slugs", ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id", using: :btree
add_index "friendly_id_slugs", ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type", using: :btree

的routes.rb

Rails.application.routes.draw do
  mount Ckeditor::Engine => '/ckeditor'

  resources :vans
  devise_for :users
  # Change get method for user signout 
  devise_scope :user do
    get '/users/sign_out' => 'devise/sessions#destroy'
  end


  root 'pages#index'

  resources :categories 
  resources :products
  resources :drivers
  resources :product_items
  resources :baskets
  resources :orders
  resources :customers

  match '/areascovered', to: 'pages#areascovered', via: :get

  match '/deliveryschedule', to: 'pages#deliveryschedule', via: :get

  match '/news', to: 'pages#news', via: :get

  match '/faqs', to: 'pages#faqs', via: :get

  match '/about', to: 'pages#about', via: :get

  match '/contact', to: 'pages#contact', via: :get

  get "baskets" => "baskets#show", :as => "current_basket"
end

1 个答案:

答案 0 :(得分:0)

您需要在控制器中使用友好的find方法。例如,而不是

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

您应该使用:

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

另外,请注意两次执行find操作的情况。例如,在您的BasketsController#show操作中,您正在调用set_basket(当前调用Basket.find(params[:id]),并且您应该通过{{1}更改为执行Basket.friendly.find(params[:id])然后,您在before_action操作的主体中再次设置相同的实例变量。您的#show操作应该只是:

BasketsController#show