0

I've stumbled across this answer and it has helped me to generate a list of unique values exactly as I wanted, however, I don't want all of the results. Is there any way to filter the results within the select or another way to accomplish this?

I was thinking of something along the lines of this:

@results = MyModel.select("DISTINCT(columnForDistinction)", :myBoolean => false)

or

@results = MyModel.select("DISTINCT(columnForDistinction)", :someString => stringImLookingFor)

Currently, I'm not able to filter the results on the query, so I am iterating over the returned array and only listing the results that have that boolean set to false like so:

<% @results.each do |result| %>
  <% if !result.myBoolean %>
    #do stuff here
  <% end %>
<% end %>

and

<% @results.each do |result| %>
  <% if result.someString == stringImLookingFor %>
    #do stuff here
  <% end %>
<% end %>

Is there a better way to be doing this?

Community
  • 1
  • 1
RileyE
  • 10,874
  • 13
  • 63
  • 106
  • `MyModel.select(:some_field).uniq` that should generate `=> SELECT DISTINCT some_field FROM my_model` – Orlando May 12 '13 at 18:33
  • @Orlando Won't that only return me that field? I want every field, but only the results that meet a certain condition. – RileyE May 12 '13 at 18:57
  • @Orlando And how would that allow me to have an additional condition? – RileyE May 12 '13 at 19:00

1 Answers1

1

ActiveRecord query methods are chainable. You can call multiple and it will build them all into a query when you use the result. For conditions, you'll use where. Try something like:

@results = MyModel.select("DISTINCT(columnForDistinction)").where(:myBoolean => false)
mckeed
  • 9,719
  • 2
  • 37
  • 41
  • Yeah. I just learned about chaining ActiveRecord queries, so this is what I needed. Does chaining hit the database more than once? – RileyE May 12 '13 at 20:33
  • No, query methods like `select` and `where` return ActiveRecord::Relation objects. Then when you call a method like `each` or `inspect` that needs the actual results, the relation object builds the DB query with all the chained stuff and runs it. I also recommend reading up about scopes. – mckeed May 12 '13 at 20:49