John
John

Reputation: 13735

Using an if statement with Rails ActiveRecord find method

I want to check that a user is included in a group. In an attempt to do this, I have the following statement:

user_id = current_user.id
unless (group.user.find(user_id))
  redirect_to different_path
end

Looking at the docs, "A failure to find the requested object raises a ResourceNotFound exception if the find was called with an id." How do I write the unless statement so that it operates properly?

Upvotes: 0

Views: 437

Answers (2)

Yuriy Goldshtrakh
Yuriy Goldshtrakh

Reputation: 2014

You can handle the redirect as part of Exception handling

redirect_to path if group.user.find(user_id)

rescue ResourceNotFound
  redirect_to differenct_path
end

alternatively and probably a better way would be to build your logic around

user.groups.include?(group)

Upvotes: 1

Ben
Ben

Reputation: 13645

If you defined a relation between group and users, you can call current_user.group.present? This will return false if there is no related object.

Upvotes: 2

Related Questions