开发者

How to return a string for rails view

开发者 https://www.devze.com 2023-04-05 06:22 出处:网络
Use method in helper to hide or show a link accordingly. The method new_cate? works as designed. However the method link_to_edit? causes the following error:

Use method in helper to hide or show a link accordingly. The method new_cate? works as designed. However the method link_to_edit? causes the following error:

undefined local variable or method `cate' for #<#<Class:0x4ed6a10>:0x4ed2d38>

Extracted source (around line #23):

20:   <tr>
21:     <td><%= cate.name %></td>
22:     <td><%= cate.description %></td>
23:     <td><%= link_to_edit? %>></td>
24: 
25:   </tr>
26: <% end %>

Here is the code:

in index.html.erb

<body>

<h2>Category</h2>
<table>
  <tr>
    <th>Category</th>
    <th>Description</th>

  </tr>

<% @categories.each do |cate| %>
  <tr>
    <td><%= cate.name %></td>
    <td><%= cate.description %></td>
    <td><%= link_to_edit? %>></td>

  </tr>
<% end %>
</table>

  <%= new_cate? %>

</body>

in categories_helper.rb

  def new_cate?
    if session[:eng_dh] 
      return link_to 'New Category', new_category_path开发者_JAVA技巧
    end
  end

  def link_to_edit?
    if session[:eng_dh]
      return link_to 'Edit', edit_category_path(cate)
    end
  end

The code following "return" seems weird. new_cate? works as designed. But link_to_edit? does not.

Any thoughts? Thanks.


You are referring to a method scope variable (which is not yet declared in that scope).

I guess what you want is

#in controller
def link_to_edit cate
if session[:eng_dh]
  return link_to 'Edit', edit_category_path(cate)
end

end

#in view
<% @categories.each do |cate| %>
  <tr>
    <td><%= cate.name %></td>
    <td><%= cate.description %></td>
    <td><%= link_to_edit cate %>></td>

  </tr>
<% end %>


There is a problem in your link_to_edit function.

In your view pass the variable cate.

<td><%= link_to_edit(cate) %></td>

and in the controller

  def link_to_edit(cate)
    if session[:eng_dh]
      return link_to 'Edit', edit_category_path(cate)
    end
  end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号