计算在搜索中返回的记录 - ROR

时间:2010-01-03 19:03:31

标签: ruby-on-rails search controller

我正在尝试让Rails返回搜索中返回的记录数(找到搜索结果);我可以让Rails使用

计算记录总数
  

Inventory.count

然而,当我进入@ advsearch.count时,它会爆炸。有任何想法吗?下面的代码是我的控制器:

  def new
    @advsearch = Advsearch.new
  end

  def create
    @advsearch = Advsearch.new(params[:advsearch])
    if @advsearch.save
      flash[:notice] = "Mr. Roboto dug through #{(Inventory.count)} records"
      redirect_to @advsearch
    else
      render :action => 'new'
    end
  end

其次是我的模型:

class Advsearch < ActiveRecord::Base

  def inventories
  @inventories ||= find_inventories
  end

  private

    def find_inventories
        Inventory.find(:all, :conditions => conditions)
    end

    def keyword_conditions
        ["inventories.item LIKE ?", "%#{keywords}%"] unless keywords.blank?
    end

    def vender_conditions
        ["inventories.vender_id = ?", vender_id] unless vender_id.blank?
    end

    def area_conditions
        ["inventories.area_id = ?", area_id] unless area_id.blank?
    end

    def chem_conditions
        ["inventories.chem_id = ?", chem_id] unless chem_id.blank?
    end

    def location_conditions
        ["inventories.location_id = ?", location_id] unless location_id.blank?
    end

    def instock_conditions
        ["inventories.instock = ?", instock] unless instock.blank?
    end

    def conditions
        [conditions_clauses.join(' AND '), *conditions_options] 
    end

    def conditions_clauses
        conditions_parts.map { |condition| condition.first }
    end

    def conditions_options
        conditions_parts.map { |condition| condition[1..-1] }.flatten
    end

    def conditions_parts
        private_methods(false).grep(/_conditions$/).map { |m| send(m) }.compact
    end
end

1 个答案:

答案 0 :(得分:4)

def create
  @advsearch = Advsearch.new(params[:advsearch])
  if @advsearch.save
    flash[:notice] = "Mr. Roboto dug through #{(@advsearch.inventories.length)} records"
    redirect_to @advsearch
  else
    render :action => 'new'
  end
end

应该让你算一算。