NameError - 在控制器中调用创建的方法时未定义的局部变量或方法

时间:2011-05-02 03:03:33

标签: ruby-on-rails model-view-controller methods nameerror

尝试访问“原因索引”页面时

NameError in Reasons#index

Showing /home/alec/workspace/rails/nwis/app/views/reasons/index.html.erb where line #26 raised:

undefined local variable or method `upvote_reason' for #<#<Class:0x000000023d9940>:0x000000023d3298>
Extracted source (around line #26):

23:     <td><%= link_to 'Show', reason %></td>
24:     <td><%= link_to 'Edit', edit_reason_path(reason) %></td>
25:     <td><%= link_to 'Destroy', reason, :confirm => 'Are you sure?', :method => :delete %></td>
26: <td><%= link_to "Vote up", :action => upvote_reason, :id => reason.id %></td>
27:   </tr>
28: <% end %>
29: </table>
Rails.root: /home/alec/workspace/rails/nwis

Application Trace | Framework Trace | Full Trace
app/views/reasons/index.html.erb:26:in `block in _app_views_reasons_index_html_erb__2084449067598068298_18776480__4598497200926455905'
app/views/reasons/index.html.erb:16:in `each'
app/views/reasons/index.html.erb:16:in `_app_views_reasons_index_html_erb__2084449067598068298_18776480__4598497200926455905'
app/controllers/reasons_controller.rb:7:in `index'

视图中的行:

<td><%= link_to "Vote up", :action => upvote_reason, :id => reason.id %></td>

控制器中的方法:

def upvote_reason
    @reason = Reason.find(params[:id])
    @reason.upvote += 1
    @reason.save
    redirect_to reason_path
end

不可否认,我对Rails很陌生,但是一旦我弄清楚如何正确地与控制器交互,我觉得我已经濒临点击了。如果有人可以指出我正确的方向来完成一个涵盖这个主题的教程,我很乐意看看这是否是一个问题的基础。

1 个答案:

答案 0 :(得分:3)

在它前面放一个冒号把它变成一个符号,或在它周围加上引号:

:action => :upvote_reason

:action => "upvote_reason"

此外,您还需要更新路线。虽然你目前可能只有resources :reasons,但你会想要这样的东西:

resources :reasons do
  get "upvote_reason", :on => :member
end

事实上,添加此路线后,您只需使用指定的路线,而不是:action:id参数:

<%= link_to "Vote up", upvote_reason_reason_path(reason) %>

(如果您只是将upvote_reason操作重命名为upvote,那么这将变为upvote_reason_path(reason)