2

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

wow can't believe I didn't think of that. Worked like a charm thanks for your help @AshutoshTiwari
0

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

4 Comments

The risk of using scopes here is that if no records match the criteria, all Gear records are returned.
Using Gear.mini.primary will not combine the conditions with a logic or but with an AND, therefor no result at all can be returned with Gear.mini.primary
Ashutosh's answer worked but I believe your answer @aspencer8111 could work as a solution for stackoverflow.com/questions/29494696/… if you could take a look at it and give your thoughts please
Yes. Because the scopes chain using "AND", MrYoshiji is right and you are right on that answer working for your other Stackoverflow quesiton.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.