Bye
Bye

Reputation: 768

Rails: undefined method error when move codes from view to helper file

In approval.html.erb

<% @approval.each do |approval| %>
    <td><%= Material.find_by_id(approval.material_id).m_name%></td>
<% end %>

I want to move Material.find_by_id(approval.material_id) to approval helper file.

In approval_helper.rb

def approval_material
  Material.find_by_id(approval.material_id)
end

Then, I modify approval.html.erb

<% @approval.each do |approval| %>
    <td><%= approval_material.m_name%></td>
<% end %>

However, it shows me an error

undefined local variable or method `approval'

What causes the error , how to fix it ? Thanks

Upvotes: 1

Views: 87

Answers (1)

Alejandro Escobar
Alejandro Escobar

Reputation: 174

You need to pass a parameter to the helper methodapproval_material method. Something like:

def approval_material(approval)
  Material.find_by_id(approval.material_id)
end

And then on your view you can call it like:

<% @approval.each do |approval| %>
    <td><%= approval_material(approval).m_name%></td>
<% end %>

Upvotes: 3

Related Questions