Ruby on rails RubyonRails访问使用.last找到的记录的属性

Ruby on rails RubyonRails访问使用.last找到的记录的属性,ruby-on-rails,Ruby On Rails,在我的资源索引视图中,当它在每个资源中循环时,我希望显示最近的场景名称。我正在使用.last提取最近的记录。当我检查返回的内容时,我可以看到值。问题是,当我试图访问所返回内容的一个属性时,会得到一个未定义的方法 例如,如果我这样做: <%= (asset.scene_assignments.where(asset_id: asset).order("created_at").last).scene_id %> <%= (asset.scene_assignments.wher

在我的资源索引视图中,当它在每个
资源中循环时,我希望显示最近的场景名称。我正在使用.last提取最近的记录。当我检查返回的内容时,我可以看到值。问题是,当我试图访问所返回内容的一个属性时,会得到一个未定义的方法

例如,如果我这样做:

<%= (asset.scene_assignments.where(asset_id: asset).order("created_at").last).scene_id %>
<%= (asset.scene_assignments.where(asset_id: asset).order("created_at").last).inspect %>
它打印这个:

场景标识:4,场景标识:3,资产标识:1,到达时间:零,创建时间:“2014-10-16 01:43:50”,更新时间:“2014-10-16 01:43:50”,位置标识:1,资产角色标识:1

为什么我不能访问返回的属性之一

在我的资产索引视图中,我有:

<% @assets.each do |asset| %>
  <tr>
    <td><%= asset.name %></td>
    <td>
      <%= (asset.scene_assignments.where(asset_id: asset).order("created_at").last).inspect %>
    </td>
    <td><%= link_to 'Show', asset %></td>
    <td><%= link_to 'Edit', edit_asset_path(asset) %></td>
    <td><%= link_to 'Destroy', asset, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

我的资源和场景之间的关系设置如下:

class SceneAssignment < ActiveRecord::Base
  belongs_to :scene
  belongs_to :asset
  belongs_to :location
  belongs_to :asset_role
  belongs_to :incident

  accepts_nested_attributes_for :asset
end

class Scene < ActiveRecord::Base
  has_many :scene_assignments
  has_many :assets, :through => :scene_assignments
  belongs_to :incident
  belongs_to :scene_type

  accepts_nested_attributes_for :scene_assignments, :allow_destroy => true
end

class Asset < ActiveRecord::Base
  has_many :scene_assignments
  has_many :scenes, :through => :scene_assignments
end
class SceneAssignment:场景\u分配
属于:事件
属于:场景类型
接受以下内容的\u嵌套\u属性\u:scene\u assignments,:allow\u destroy=>true
结束
类别资产:场景\u分配
结束

我认为是
.scene\u id
而不是
.last
导致了您的错误。“.”的结果,其中(…)是记录的集合,而不是单个记录

要解决这个问题,您可以说
asset.scene\u assignments.where(asset\u id:asset).order(“created\u at”).last.first.scene\u id
,但这会让一些相当混乱的代码变得更糟。:)