I have 3 roles for User, call it standard, premium, and admin. Each can post posts. Premium and admin can choose whether to make private post or non private post (private: false or private: true). Standard user will not be given the option to choose whether their Post will be private/ not; by default, all of standard user's posts will have Private: nil status.
To summarize:
I am trying to make a scope so that when a standard user views index page, they see posts with Private: nil and Private: false, while Premium and Admin user can view all. My problem is, I can't come up with a ternary operators that allows standard users to view both private: nil and private: false Posts.
This is what I have on Post model:
scope :visible_to, -> (user) { user.admin? || user.premium? ? all : where(private: false) || where(private: nil)}
The code above only displays Posts with private: false. I've tried various combination:
... where(private: false || nil)}
Displays only private: false posts
... where(private: nil || false)}
Displays only private: nil posts
... where(private: nil && false)}
Displays only private: nil posts
... where(private: false && nil)}
Displays only private: false posts
and several other combinations -
I also noticed that when I switched the order of false and nil, it displays different results. I thought || or && operators are non-commutative. Maybe there is something about scoping or ternary operators that I was not aware...
Thanks!
It sounds like your just wondering how to do an or operator in a where? http://guides.rubyonrails.org/active_record_querying.html
Section 2.3.3 Subset Conditions
... where(private: [false, nil])}
This should convert it into the sql
WHERE private in (false, nil)
Which is shorthand for multiple or statements in sql. You can also use arel tables for more advanced sql features without breaking down to pure sql strings. Checkout out this article about your case using IN along with arel examples
https://robots.thoughtbot.com/using-arel-to-compose-sql-queries
# It even handles arrays containing nil!
where(foo: ['bar', 'baz', nil]) # => (WHERE foo IN ('bar', 'baz') OR foo IS NULL)