shou2017.com
JP

rails, using the where method to search on complex criteria

Sat Aug 5, 2017
Sat Aug 10, 2024

If you want to list them, just do so below, but it is too simple to be complicated.

def index
  @samples = Sample.all
end

For more, complex things, use query methods.

Frequently used ones.

Methods Summary
where filtering by condition
not expresses a negative conditional expression
order sorting
reorder override sort expression
select specify columns
distinct get records with no duplicates
limit specify records to be extracted
offset specify the number of records to start extracting, used with limit
group group the results by a specific key
having GROUP BY with additional constraints
joins with other models
includes Get all related models at once
readonly make retrieved objects read-only
none retrieve an empty result set

Use with the where method to make sure only what you create is displayed.

def index
  @samples = Sample.all
end

If you simply use ALL, you will see not only your own, but also those of other users, so you can use the where method to make sure that only yours are displayed. The example below means to filter only those that are identical to the current user and the user who created the SAMPLE.

def index
  @samples = Sample.where(user_id: current_user.id)
end
See Also