【问题标题】:Count records returned in a search - ROR计算搜索中返回的记录 - ROR
【发布时间】:2011-01-01 00:58:43
【问题描述】:

我试图让 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

【问题讨论】:

  • 你拼错了“vendor”,仅供参考。
  • 你能粘贴你得到的错误信息吗?还有你在哪里使用@advsearch.count ?
  • 1. NoMethodError undefined method count 2. 我在这种情况下使用它: flash[:notice] = "The search 挖掘了#{(Inventory.count)} 记录并找到了#{@advsearch.count}"

标签: ruby-on-rails search controller


【解决方案1】:
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

应该让你数一数。

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多