Url正在使用正确的参数,但未在rails应用中显示正确的结果

时间:2017-03-06 08:12:47

标签: ruby-on-rails ruby

我正在尝试根据类别和子类别进行过滤。现在我没有任何ajax这样做。

以下是我的控制器方法

def filter 
    x = params[:category_id]
    y = params[:sub_category_id]
    #@wanted_equipments = WantedEquipment.Approved.where(category_id: "#{x}", sub_category_id: "#{y}")

    if x
      @wanted_equipments = WantedEquipment.Approved.where(category_id: "#{x}")
    elsif x && y
      @wanted_equipments = WantedEquipment.Approved.where(category_id: "#{x}", sub_category_id: "#{y}")
    end
end

当我第一次根据类别进行过滤时,网址如下所示:

http://localhost:3000/wanted_equipments/filter?utf8=%E2%9C%93&category_id=1

并显示该类别下的设备。 接下来,当我选择子类别并输入过滤器时。网址如下所示:

http://localhost:3000/wanted_equipments/filter?utf8=%E2%9C%93&category_id=1&sub_category_id=3 

应该根据sub_category_id进一步过滤。但是它显示的是与之前相同的数据,即它只考虑category_id作为参数,即使url采用了sub_category_id。

我知道我做错了什么。我尝试了不同的条件,但却无法解决这个问题。有人可以告诉我如何更改控制器以便它也考虑子类别?

3 个答案:

答案 0 :(得分:2)

问题与您的if条件有关。尝试改为:

if x && y
  @wanted_equipments = WantedEquipment.Approved.where(category_id: "#{x}", sub_category_id: "#{y}")
elsif x
  @wanted_equipments = WantedEquipment.Approved.where(category_id: "#{x}")
end

因为您的if x条件为true,所以它不会移动到eslif块。希望这有效。

答案 1 :(得分:1)

有顺序问题

在您的代码条件中,首先检查present?是否x如果if x && y @wanted_equipments = WantedEquipment.Approved.where(category_id: "# {x}", sub_category_id: "#{y}") elsif x @wanted_equipments = WantedEquipment.Approved.where(category_id: "#{x}") end 存在,那么它将不会检查第二个条件

因此,请按照以下方式更改您的代码序列

Review Details | Rating
"The Nokia 3310 is one of my favorite mobile phones and the new phone makes me happy"   | 7
"Talking about phone there is nothing else than Apple comes to my mind, the I phone 7 is the best in market"    | 9
"Samsung J7 doesn’t live up to the expectations and its not worthy for the price"   | 1
"I am not a Big fan of I Phone 7, opt for something cheaper and save money" | 3

答案 2 :(得分:0)

     @wanted_equipments = if y
                           WantedEquipment.Approved.where(category_id: "#{x}", sub_category_id: "#{y}")
                          else
                           WantedEquipment.Approved.where(category_id: "#{x}")
                          end if x