Rails处理nil / undefined方法

时间:2019-01-21 19:09:58

标签: ruby-on-rails

我正在尝试将名为/ categories的内容全部移至/ digital-catalog。

我正在重定向所有内容,并且可以正常运行,但是当不存在url_name时输入失败。

我是一个三元运算符的新手,但看起来好像失败了。

代码在以下位置失败:

- custom_search_path = action_name == 'show' ? category_path(@category.url_name) : digital_catalog_path
.search-cont
 = form_tag custom_search_path, id: 'search-filter', method: :get do
   = search_field_tag :search_input, params[:search_input], placeholder: 'Search', class: 'form-control'
   - if params[:search_input]
     = link_to 'x', custom_search_path, class: 'add-on'
   = submit_tag 'go'

确切的错误消息是:

  

类别#show中的NoMethodError

     

nil:NilClass的未定义方法“ url_name”

我的CategoriesController看起来像:

class CategoriesController < ApplicationController
  respond_to :html, :json
  before_action :load_category, only: [:show]
  before_action :require_user

  def index
    @categories = Category.ordered.search(params[:search_input]).paginate(page: params[:page])
    respond_with @categories
  end

  def show
    if @category.nil?
      redirect_to '/'
    else
      @items = @items.search(params[:search_input]).paginate(page: params[:page])
      @response = { category: @category, items: @items }
      respond_with @response
    end
  end

  private

  def load_category
    @category = Category.find_by!(url_name: params[:id])
    @items = @category.items
    add_breadcrumb 'categories', digital_catalog_path
    add_breadcrumb @category.name
  end
end

当有人输入与此处不匹配的网址时,我该如何处理?

我尝试用以下方法代替助手:

def route_category
 if action_name == 'show'
   redirect_to digital_catalog_path(@category.url_name)
 else
   redirect_to root_path
 end
end

最终以未定义的方法“ redirect_to”结束,老实说,这不能解决表单标签获取正确数据的问题。

编辑:

我也尝试过相同的错误消息:

def show
 if @category.url_name.nil?
   redirect_to root_path
 else
   @items = @items.search(params[:search_input]).paginate(page: params[:page])
   @response = { category: @category, items: @items }
   respond_with @response
 end
end

那么我该如何处理不存在的网址?

编辑:我添加了整个CategoriesController。加上我认为可以解决错误的show方法的更新,但不会。

1 个答案:

答案 0 :(得分:0)

我仍然没有找到将其发送到404页面的正确方法,但这是我的权宜之计:

def show
 if @category
   @items = @items.search(params[:search_input]).paginate(page: params[:page])
   @response = { category: @category, items: @items }
   respond_with @response
 else
   redirect_to digital_catalog_path
 end
end

private

def load_category
  begin
    @category = Category.find_by!(url_name: params[:id])
    @items = @category.items
    add_breadcrumb 'categories', digital_catalog_path
    add_breadcrumb @category.name
  rescue ActiveRecord::RecordNotFound => e
    @category = nil
  end
end
相关问题