Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Check if User Id is in Array

I'm trying to build a condition based on wether or not a "user" is a "member". Basically I need a way of checking if the current_user.id matches any of the user_id of any members. The non-working code I have right now is:

<% if current_user = @page.members %>
  you can view this content.
<% end %>

I'm looking for something along the lines of: "If current_user.id exists in the "user_id" of any members."

like image 977
BTHarris Avatar asked Apr 23 '12 23:04

BTHarris


2 Answers

Something like this, based on the field names in your question:

<% if @page.members.map(&:user_id).include? current_user.id %>
  You can view this content
<% end %>
like image 165
Mark Reed Avatar answered Oct 02 '22 08:10

Mark Reed


Assuming your @page.members variable contains an array, you can use the include? method:

<% if @page.members.include? current_user %>
  you can view this content.
<% end %>

If you're using an array of ids, you will of course need to change the test slightly to look for the current user's id:

<% if @page.members.include? current_user.id %>
  you can view this content.
<% end %>
like image 22
rjz Avatar answered Oct 02 '22 08:10

rjz