How to make this 'if' statement work after switching to a habtm setup?

Alright, so I'm very new to rails, so please forgive me if some of these questions seem trivial.

I'm working on a group project in which users view/create the projects that exist, and the projects can display a list of associated users within it. Someone had originally set it up as one-to-many relationship and we had to make it a habtm association.

What I'm asking is how do I make this if statement work that was originally:

       <strong><%= if project_model.user %></strong><br />
        <% if project_model.user == current_user %><br />

Now project_model should have a database/list within project_model.users (a .build was used when creating the project_model so it should at least contain the current_user. Hopefully....)

Something to note: @project_models is defined in the controller, but this is in a 'do' where @project_models.each do |project_models|

Side note: Some of the things one of my group members did is a little outside the scope of the class and so I'm a bit lost on what some of his code is actually doing. If someone could explain what the if project_model.user contained within the <strong> is actually doing, it would also be really helpful.


Are you asking how to find out if project_model is associated with current_user? If so, try this:


Also, this statement: if project_model.user

is trying to see if project_model has an existing associated user before attempting to access its name property. If the property_model does not have a user, then property_model.user will return nil. The if statement will treat this as a false value and therefore will not execute the code before it. This avoids a

NoMethodError: undefined method `name' for nil:NilClass

error if project_model.user doesn't exist. However, since you've changed to a habtm association, one ProjectModel can have multiple User's. Perhaps you want to use a project_model.users.each call to display all of the users for the project_model instead?

The way it is written here suggests a Project used to have one user (project.user is singular). Now you have many users working on a same project which should translate to: project.users (notice users is plural) meaning you're dealing with a list of users.

The 2nd if statement checks if you're part of a project before showing you stuff only involved users can know. So you can replace:

<% if project_model.user == current_user %>
# by
<% if %>

Since we're dealing with a list of users now you also need to iterate through te users you want to display.

So you could replace :

<%= if project_model.user %>
# by
<%=", ") %>

Need Your Help