Mel Mel - 3 months ago 6
Ruby Question

Rails 4 - how to use a helper method in the parent view

I'm trying to figure out how to use helpers files.

I have models for Project and Potential Use. The associations are:

Project

has_many :potential_uses
accepts_nested_attributes_for :potential_uses, reject_if: :all_blank, allow_destroy: true


Potential Use

belongs_to :project
belongs_to :user


In my projects show page, I have a reference to a helper method defined in my projects helper folder:

<%= potential_uses_for_viewer(@project) %>


The helper method (in projects_helper.rb) has:

def potential_uses_for_viewer(project)
if @current_user.id == @project.profile.user_id
render 'potential_uses/private_comments'
else
render 'potential_uses/open_comments'
end
end


I have two view partials in my potential uses view folder. I want to render one of those partials if the current user is the project creator, and another if the current user is not the project creator.

Presently, there are no errors that are rendered, but the helper in the projects folder does not work. Regardless of whether I am logged in as the user that made the project or not, I get the potential_uses/open_comments view.

Can anyone see where I've gone wrong?

Answer

You're receiving an argument project in the helper but inside the helper method, you're trying to access @project.profile.user_id. @project is nil inside the helper. You should use

if @current_user.id == project.profile.user_id 
  render 'potential_uses/private_comments'
Comments