Ruby on rails 将作用域与.last一起使用将返回视图中的AssociationRelation

Ruby on rails 将作用域与.last一起使用将返回视图中的AssociationRelation,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,客户机具有多种状态。为了获得最新状态,我在status上使用以下作用域 scope :latest, -> { order(:created_at).last } 这在Rails控制台中可以正常工作 client = Client.last client.statuses.latest => #<Status id:... client.statuses.latest.stage => 1 这将按预期返回一个状态对象:#请注意所有作用域方法将返回一个ActiveRec

客户机具有多种状态。为了获得最新状态,我在
status
上使用以下作用域

scope :latest, -> { order(:created_at).last }
这在Rails控制台中可以正常工作

client = Client.last
client.statuses.latest
=> #<Status id:...
client.statuses.latest.stage
=> 1

这将按预期返回一个
状态
对象:
#请注意所有作用域方法将返回一个ActiveRecord::Relation

我会像这样重构你的模型来解决这个问题,并且仍然得到相同的功能

 class Status < ActiveRecord::Base
    ....
    scope :newest, -> { order(:created_at) }

    def self.latest
       Status.newest.first
    end
 end

奇怪的
stage
是属性还是状态为
的方法?你能提供吗?
stage
只是
Status
上的一个属性,它返回控制台中预期的整数。谢谢你的建议。同样,这在控制台中起作用,但是在查看
未定义的方法阶段为nil:NilClass
抛出以下异常。检查Rails日志中的SQL查询,那里有一些作用域没有返回任何内容,如果您首先得到nil,那么这意味着关系开始是空的
undefined method `stage' for #<ActiveRecord::AssociationRelation []>
undefined method `foobar' for #<Status:0x007ff615fcdb28>
<%= f.object.statuses.latest.stage unless f.object.statuses.latest.blank? %>
 class Status < ActiveRecord::Base
    ....
    scope :newest, -> { order(:created_at) }

    def self.latest
       Status.newest.first
    end
 end
client = Client.last
client.statuses.latest