如何从单个活动记录对象获取列值

时间:2019-12-06 14:06:23

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

我从表中获得Issue对象

@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):

1 个答案:

答案 0 :(得分:3)

@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)

但是,如果找不到该记录,则会生成运行时错误。