byCoder
byCoder

Reputation: 9184

Rails has_scope with if condition

In my form i have a lot of fields, and when i submit my form im my url i see a lot of empty params, like url?a=&b=&c= and my has_scope model think that i want to use this params, but with null value, but this is wrong.

Part of my model and controller:

class CarsController < ApplicationController
 has_scope :by_manufacturer
 has_scope :by_price, :using => [:price_from, :price_to]
end

class Car < ActiveRecord::Base
 scope :by_manufacturer, -> vehicle_manufacturer_id { where(:vehicle_manufacturer_id => vehicle_manufacturer_id) }
 scope :by_price, -> price_from, price_to { where("price >= ? AND price <= ?", price_from, price_to) }
end

How could i write something like:

if vehicle_manufacturer_id.present? 
 has_scope :by_manufacturer
end

how is it right to check on field presense? And where to write in and how?

Upvotes: 2

Views: 2867

Answers (1)

rails4guides.com
rails4guides.com

Reputation: 1441

Has_scope has an :if condition you can use to determine when the scope should be used. Example:

has_scope :by_manufacturer, if: vehicle_manufacturer_id.present?

Or add an condition to the scope itself:

scope :by_manufacturer, -> vehicle_manufacturer_id { where(:vehicle_manufacturer_id => vehicle_manufacturer_id) if vehicle_manufacturer_id.present? }

I cannot test it right now, but this should work. However, I don't think your problem is wether or not you call the scope. The URL params are passed on from your view to your controller. The scope only determines what records return given certain conditions, they say nothing about what URL params should be shown.

Upvotes: 2

Related Questions