【问题标题】:Scope declaration in model not working模型中的范围声明不起作用
【发布时间】:2012-07-06 02:04:29
【问题描述】:

我正在使用 Ruby on Rails 3,并在我的对象类中创建了一些范围,但是当我从我的代码中调用它们时,它会返回一个错误:

irb>Transaction.first.committed

=> # 的未定义方法“已提交”

对象类:

类事务<:base>

 attr_accessible :amount, :description, :published, :task_description_id, :discrete_task_id, :transaction_type

 belongs_to :discrete_task

 scope :committed, where(:transaction_type => "committed")

 scope :obligated, where(:transaction_type => "obligated")

 scope :expensed, where(:transaction_type => "expensed")

结束

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您不能在单个 Transaction 对象(实例)上调用作用域(类方法)。

    你必须这样做:

    Transaction.committed
    

    你得到一个ActiveRelation(本质上是一个Array,但你可以在上面调用其他作用域)。

    无论如何,您希望Transaction.first.committed 做什么?您将拥有一个对象,然后您将尝试查找其 transaction_type 的“已提交”位置。您已经拥有该对象,因此您可以调用它的#transaction_type 方法。

    作用域将带回所有具有已提交事务类型的事务对象。如果您想要一个 instance 方法来告诉您是否提交了一个 single 对象,那么您必须创建一个实例方法,例如:

    def committed?
      transaction_type == "committed"
    end
    

    那么你可以写:

    Transaction.first.committed? # => true
    

    【讨论】:

      【解决方案2】:

      Transaction.first 将返回一个Transaction 对象,因此您不能在其上调用where。试试:

      Transaction.committed.first
      

      【讨论】:

        猜你喜欢
        • 2015-03-11
        • 2013-05-05
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多