user2926036
user2926036

Reputation:

Add search parameter if condition is true

I have code in my controller where i want filter some records for non-authorized users:

unless admin_signed_in?
  @posts = Post.where(hidden: false)
else
  @posts = Post.all
end

I tried to refactoring this, but can't make right query

@posts = Post.where(hidden: if admin_signed_in? ? true : false )

Output:

.../app/controllers/posts_controller.rb:7: syntax error, unexpected ')', expecting keyword_then or ';' or '\n' in_signed_in? ? true : false )

Upvotes: 1

Views: 76

Answers (4)

Stefan
Stefan

Reputation: 114218

unless with else is quite confusing. I'd change it to:

if admin_signed_in?
  @posts = Post.all
else
  @posts = Post.where(hidden: false)
end

Other than that, I think the code reads just fine.

However, you could replace it with a ternary operator:

@posts = admin_signed_in? ? Post.all : Post.where(hidden: false)

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36860

The problem with the ternary is the "if"

@posts = Post.where(hidden: if admin_signed_in? ? true : false )

Should be

@posts = Post.where(hidden: admin_signed_in? ? true : false )

And of course you can consider the other solutions posted.

Stefan has pointed out that admins will only see hidden posts, not all posts, so if you're going to stick with the ternary then you really want...

@posts = Post.where(hidden: admin_signed_in? ? [true,  false, nil] : false )

Upvotes: 2

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

You have an syntax error. you are using both if and ternary (? :). Just change it to

@posts = Post.where(hidden: admin_signed_in?)

You don't need to pass true and false manually

NOTE: But, it will not return you the posts with hidden = false if admin_signed_in? returns true

So, you might want to change it to

@posts = Post.where(({hidden: true} if admin_signed_in?))

Upvotes: 4

spickermann
spickermann

Reputation: 106972

I think your refactoring will not work, because Post.all will not return the same as Post.where(hidden: true). The later will only list posts that are hidden, but not visible ones.

I would refactor the code to something like:

@posts = Post.all
@posts = @posts.where(hidden: false) unless admin_signed_in?

Upvotes: 2

Related Questions