未定义的方法`范围&#39;对于#<class:0x007f8c61c41c98>

时间:2018-06-08 10:20:18

标签: ruby-on-rails ruby-on-rails-4

尝试制作搜索功能时出现此错误。这是我的代码。

 class CatalogController < ApplicationController
  before_filter :initialize_cart, :except => :show
  #before_filter :require_no_user
  def show
    @disc = Disc.find(params[:id])
    @page_title = @disc.title
  end

  def index
    @discs = Disc.order("discs.id desc").includes(:artists, :producer).paginate(:page => params[:page], :per_page => 5)
    @page_title = 'Catálogo'
  end

  def latest
    @discs = Disc.latest 5 # invoques "latest" method to get the five latest discs
    @page_title = 'Últimos discos'
  end

  def search
    @page_title = "Buscar"
    if params[:title] 
      @discs = Disc.find_with_ferret(params[:title])
      #@discs = Disc.where("title like ?", "%#{params[:title]}")
    unless @discs.size > 0
        flash.now[:notice] = "No se han encontrado discos con la búsqueda establecida."
      end
    end
  end

  def rss
    latest
    render :layout => false
    response.headers["Content-Type"] = "application/xml; version=1.0; charset=utf-8"
  end
end

这是disc.rb

  class Disc < ActiveRecord::Base


  has_and_belongs_to_many :artists
  belongs_to :producer

  acts_as_ferret :fields => [:title, :artist_names]

  has_many :cart_items
  has_many :carts, :through => :cart_items

  has_attached_file :cover_image
  validates_attachment :cover_image,
  :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] }

  validates_length_of :title, :in => 1..255, :message => 'El título no puede estar en blanco'
  validates_presence_of :producer, :message => 'Se necesita al menos una productora'
  validates_presence_of :artists, :message => 'Se necesita al menos un autor'
  validates_presence_of :produced_at, :message => 'Se necesita una fecha de producción'
  validates_numericality_of :price, :message => 'Se necesita un precio en formato numérico'
  validates_length_of :serial_number, :in => 1..5 , :message => 'El número de serie tiene que estar comprendido entre 1 y 5 caracteres'
  validates_uniqueness_of :serial_number, :message => 'Este número de serie ya existe'

  def artist_names
    self.artists.map{|artist| artist.name}.join(", ")
  end

  def self.latest(num)
    all.order("discs.id desc").includes(:artists, :producer).limit(num)
  end
end

有人知道错误吗?我认为问题不是定义范围,而是没有想法。我正在寻找大约两个小时,但没有得到任何结果。任何人都会帮助我,我会很自豪。谢谢!

1 个答案:

答案 0 :(得分:1)

在模型文件中定义范围

scope :find_with_ferret, -> (title) {where("title like ?", "%#{title}")}