Search code examples
sqlruby-on-railsruby-on-rails-5

Rails WHERE--AND condition to find two or more values of the same attribute


I am trying to implement my own authentication system, where the logged in users is supposed to see records for the state they come from:

if current_user.role.name == "state_admin" && current_user.state.name == "Texas"
    @b = Staff.where(state_id: 3) 

The state_id for Texas is 3.

I however, I would like to create a special exemption where the Texas admin can also view records for Florida. I have written the following code to try to achieve that:

@staffs= Staff.where(state_id: 3).or(Staff.where(state_id: 4))

When I go to the index page, only the records for Texas are being displayed. I want to list records for Texas AND Florida (state_id 4).

Where I am I going wrong? I have been on it for a couple of hours and I can't seem to make it work (am a beginner though).


Solution

  • As Florent Ferry states in the comments, you can write this:

    @staffs = Staff.where(state_id: [3, 4])

    Also might be worth a read of Active Record: https://guides.rubyonrails.org/active_record_basics.html