holyredbeard
holyredbeard

Reputation: 21208

Passing value from view to helper

I have the following tables:

projects
users
projects_users <- relational table

In the view I'm looping through all the projects and render them out one and one with different classes (as well as linked or not linked)depending the relation a user has to it (owner, member, not a member).

This works well except for the if statement on line 3, where I check whether or not the user is a member. 'check_if_member' is to be found in the projects helper (see below). What happens is that I get the following error message:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

...which (if I got it right) means that either '@project.id' or 'current_user.id' is nil. In this case I'm pretty sure it's @project.id that's nil, and that it's actually not passed to the helper.

If I'm right, how do I pass it to the helper? If I'm not right, what is the problem?

the view:

1.  <% @projects.each do |project| %>
2.      <div class="project_container">
3.          <% if check_if_member %>
4.              <% if project.user_id == current_user.id %>
5.                  <div class="users_project label label-success">
6.                      Owner
7.                  </div>
8.              <% else %>
9.                  <div class="not_users_project label label-info">
10.                     Member
11.                 </div>
12.             <% end %>
13.             <div class="project_name_div">
14.                 <%= link_to (project.title), project_path(project) %><br />
15.             </div>
16.         <% else %>
17.             <div class="project_name_div">
18.                 project.title <br />
19.             </div>
20.         <% end %>
21.     </div>
22. <% end %>

the helper:

module ProjectsHelper
    def check_if_member
        if ProjectsUser.where("project_id = ? AND user_id = ?", @project.id, current_user.id)
            return true
        else
            return false
        end
    end
end

Upvotes: 0

Views: 1118

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230316

Pass explicitly

def check_if_member project, user
    ProjectsUser.where("project_id = ? AND user_id = ?", project.id, user.id).count > 0
end

Then

<% if check_if_member(project, current_user) %>

Upvotes: 2

Related Questions