aealvarez3
aealvarez3

Reputation: 49

Rails display data with specific field value

I am trying to display records that have a specific values in one of the fields.

controller

def mini
    @gears = Gear.where("Lab like ?", "%Mini%")
  end

The above code displays every record with the value "Mini" in the "Lab" field. I am now trying to make it so it displays records with two different values "Mini" and "Primary". So it would show me all records that have either "Mini" or "Primary" in the lab field.

I tried this

def mini
    @gears = Gear.where("Lab like ? AND Lab like ?","%Mini%", "%Primary%) 
  end

but it did not work. No error is thrown but no records are displayed on my front end webpage. I have also tried different variations but still no luck. Any help on this would be much appreciated.

Upvotes: 2

Views: 299

Answers (2)

aspencer8111
aspencer8111

Reputation: 786

This is a perfect use case for Scopes. See this: http://guides.rubyonrails.org/active_record_querying.html#scopes

So in your gear.rb model file, do something like:

scope :mini, -> { where(lab: 'Mini') }
scope :primary, -> { where(lab: 'Primary') }

Then in your contorller, you could do:

@gears = Gear.mini #mini gears

or

@gears = Gear.primary #primary gears

or

@gears = Gear.mini.primary #mini and primary gears

Upvotes: 0

Ashutosh Tiwari
Ashutosh Tiwari

Reputation: 998

you should use OR instead of AND.
use this Gear.where("Lab like ? OR Lab like ?","%Mini%", "%Primary%)

Upvotes: 2

Related Questions