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



>我从表中获取问题对象

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

但是,如果未找到记录,这将生成运行时错误。

最新更新