Rails范围测试在视图中

时间:2013-04-30 14:03:32

标签: ruby-on-rails

我在worequests模型中有一个范围:

scope :notcompl, where("statuscode_id != ?", Statuscode.last.id)

如果worequest不是compl,我只想在worequests show页面中显示编辑按钮。我试过这个并得到了未定义的方法:

<% if @worequest.notcompl? %>
  <= link_to 'Edit', edit_worequest_path(@worequest), :class => 'btn btn-success' %>
<% end %>

正确的语法是什么?

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

范围将找到满足您条件的所有记录。

您想要做的就是检查worequest是否statuscode_id Statuscode.last.id。你需要的是你的类而不是范围的实例方法:

 class Worequest < ActiveRecord::Base

    def not_complete?
        statuscode != Statuscode.last.id
    end
 end

然后在您看来,您可以检查Worequest是否完整:

<% if @worequest.not_complete? %>
  <= link_to 'Edit', edit_worequest_path(@worequest), :class => 'btn btn-success' %>
<% end %>

此外,定义范围会创建一个与范围同名的方法。因此,调用.notcompl与调用.notcompl?的方法不同 - 这解释了您遇到的未定义方法问题。

答案 1 :(得分:0)

范围属于模型,不属于控制器。将其移至Worequest,它应该有效。

答案 2 :(得分:0)

来自doc

  

范围:添加类方法,用于检索和查询对象。

问题是您在不在类中的实例中调用notcompl方法。 Worequest.notcompl应该有效(不是在同一个例子中)。

PS:请参阅@alexBrand回答。