Mel Mel - 4 months ago 15
Ruby Question

Rails 4 - helper method not responding to if condition

I'm trying to figure out how to use a helper method in rails 4.

I have profile show page - if the current user is looking at:
- their own profile page, they should have a menu with 6 options on that page (each option links to the visible bits of that user's profile); or else
- another user's profile page, they should have a menu with 4 options on that page (each option links to a the visible bits of that other user's profile).

In my helper folder, I have a profiles_helper.rb:

module ProfilesHelper

def items_for_profile_menu(profile)
if current_user.id = @profile.user_id
"<li class='col-xs-4 col-sm-2 nopadding menuitem' style='background:#006F7F'>
<a href='index.html' class='hvr-sweep-to-bottom'>
<br><br>
<span>Dashboard</span>
</a>
</li>"
else
"<li class='col-xs-6 col-sm-3 nopadding menuitem blue'>
<a href='resume.html' class='hvr-sweep-to-bottom'>
<i class='flaticon-graduation61'>
</i><span>Researh History</span></a>
</li>"


In my profile show, I have:

<ul id="nav" class="row nopadding cd-side-navigation">
<%= raw (items_for_profile_menu(@profile)) %>
</ul>


When I save all this and try it - I get the same 6 item menu when I am logged in as the owner of the profile, as I do when I look at the profile from another account.

How do I get this helper method to distinguish between the current user who's id is the same as the profile.user_id that is for the displayed profile and the current user's own profile page?

My model associations are:

User:

has_one :profile


Profile:

belongs_to :user

Answer

Your problem is using assignment instead of comparison.

if current_user.id = @profile.user_id 

should read

if current_user.id == profile.user_id

However, while we're looking at this, you should consider separating the view code from application logic. All of the code to output the HTML should be in the view if possible. So your helper should be simplified, example as follows:

module ProfilesHelper
  def logged_in_as?(profile)
    current_user.id == profile.user_id
  end
end

Then your profile show can be:

<ul id="nav" class="row nopadding cd-side-navigation">
  <% if logged_in_as?(@profile) %>
    <li class='col-xs-4 col-sm-2 nopadding menuitem' style='background:#006F7F'>
      <a href='index.html' class='hvr-sweep-to-bottom'>
        <br><br>
        <span>Dashboard</span>
      </a>
    </li>
  <% else %>
    <li class='col-xs-6 col-sm-3 nopadding menuitem blue'>
      <a href='resume.html' class='hvr-sweep-to-bottom'>
        <i class='flaticon-graduation61'>
        </i><span>Researh History</span></a>
    </li>
  <% end %>
</ul>

This way the HTML is all together and you don't need to mess around with your helper when you want to change it - plus, you can reuse it elsewhere for simple logic in other templates.

Comments