class Expense < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :expenses
end

class ExpensesController < ApplicationController
  def index
    if params[:concept] || params[:category_id]
        search = "%" + params[:concept] + "%"
        @expenses = Expense.where("concept LIKE ? OR category_id = ?", search, params[:category_id])


    else
     @expenses = Expense.order("date DESC")
    end
  end
end


嗨,我需要按2个参数进行搜索。概念是text_field,类别ID是select_tag。

我正在使用sqlite3。

我需要得到以下相同的结果:
http://localhost:3000/expenses

对于:
http://localhost:3000/expenses?utf8=%E2%9C%93&concept=&category_id=

如果您愿意,可以使用我的种子:

restaurantes = Category.create(name: "Restaurantes")
carro = Category.create(name: "Carro")
hogar = Category.create(name: "Hogar")

Expense.create(category: restaurantes, date: Date.current, concept: "Hamburguesas el burral", amount: 32000)
Expense.create(category: restaurantes, date: Date.current - 4, concept: "Hamburguesas el burral", amount: 45000)
Expense.create(category: carro, date: Date.current, concept: "Gasolina", amount: 80000)
Expense.create(category: hogar, date: Date.current - 6, concept: "Lámparas", amount: 350000)

最佳答案

更改范围,而不使用OR。

class ExpensesController < ApplicationController
  def index
    @expenses = Expense.order("date DESC")
    if params[:category_id].present?
      @expenses = @expenses.where(category_id: params[:category_id])
    end
    if params[:concept].present?
      @expenses = @expenses.where("concept LIKE ?", "%#{params[:concept]}%")
    end
  end
end

关于mysql - 按2个参数搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45723748/

10-12 01:44