【问题标题】:How to get column value from single active record object如何从单个活动记录对象中获取列值
【发布时间】:2019-12-06 14:06:23
【问题描述】:

我从表中获取问题对象

@issue = Issue.where(id: issue_id)

所以我有了下一个活动记录对象。

ActiveRecord::Relation::WhereClause:0x00007f88ea670f00 @predicates=[#<Arel::Nodes::Equality:0x00007f88ea670fa0 @left=#<struct Arel::Attributes::Attribute relation=#<Arel::Table:0x00007f88ea05fe68 @name="issues", @type_caster=#<ActiveRecord::TypeCaster::Map:0x00007f88ea05fee0 @types=Issue(id: integer, tracker_id: integer, project_id: integer, subject: string, description: text, due_date: date, category_id: integer, status_id: integer, assigned_to_id: integer, priority_id: integer, fixed_version_id: integer, author_id: integer, lock_version: integer, created_on: datetime, updated_on: datetime, start_date: date, done_ratio: integer, estimated_hours: float, parent_id: integer, root_id: integer, lft: integer, rgt: integer, is_private: boolean, closed_on: datetime)>, @table_alias=nil>, name="id">, @right=#<Arel::Nodes::BindParam:0x00007f88ea670fc8 @value=#<ActiveRecord::Relation::QueryAttribute:0x00007f88ea670ff0 @name="id", @value_before_type_cast=1, @type=#<ActiveRecord::ConnectionAdapters::SQLite3Adapter::SQLite3Integer:0x00007f88e6cd3950 @precision=nil, @scale=nil, @limit=nil, @range=-9223372036854775808...9223372036854775808>, @original_attribute=nil>>>]>}

使用 project_id: integer 列,但是当我尝试获取 project_id 值时 - 它引发了错误

我的代码:

project_id = @issue.project_id

错误:

NoMethodError (undefined method `project_id' for #<Issue::ActiveRecord_Relation:0x00007fdb03e0e008>
Did you mean?  object_id):

【问题讨论】:

  • 试试Issue.where(id: issue_id).pluck(:project_id)。原因:where 返回一个Issue::ActiveRecord_Relation(许多对象),project_id 意味着在单个对象中调用。 pluck 获取对应于表列传递的每个参数,并在数组中返回它们。
  • @SebastianPalma 感谢您的注意,但已经阅读了 pluck 的内容,但仍然不明白如何将 project_id 从对象获取到变量。
  • 如果你需要一条记录,那么你应该使用 find 而不是 where。试试Issue.find(issue_id).project_id
  • @SebastianPalma 是的,就是这样,SteveTurczyn 已经回答了

标签: ruby-on-rails ruby activerecord rails-activerecord


【解决方案1】:
@issue = Issue.where(id: issue_id) 

以上为您提供了一个包含一个问题的关系(如果未找到匹配项,则没有问题)。

如果你想要问题本身,你可以这样做

@issue = Issue.where(id: issue_id).take

或者更常见

@issue = Issue.find_by(id: issue_id) 

上面给出了问题(如果发现)或无。

如果您确实知道 issue_id 存在,您可以这样做

@issue = Issue.find(issue_id)

但是如果没有找到记录会产生运行时错误。

【讨论】:

  • 我会说.first.take 更惯用。
  • 我认为take 的性能稍微好一些......也许不在这个“按id 检索”示例中,但肯定在可能有多个匹配记录的其他查询中。大卫奥尔德里奇在这里介绍了这个......stackoverflow.com/a/18498255/2516474
  • 这很有趣。我没有意识到 Rails 默认会按主键排序。
猜你喜欢
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 2019-03-30
  • 2017-06-09
相关资源
最近更新 更多