Mel Mel - 1 year ago 68
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:


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 == @project.profile.user_id
render 'potential_uses/private_comments'
render 'potential_uses/open_comments'

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 Source

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 == project.profile.user_id 
  render 'potential_uses/private_comments'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download