在rails控制台中播放对象时未定义的方法`title'

时间:2014-07-09 15:27:12

标签: ruby-on-rails

2.1.1 :040 > post = Post.find(2)
Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", 2]]
=> #<Post id: 2, title: "My second post", url: "tw.yahoo.com", description: "Oh..YA"> 
2.1.1 :041 > post.title
=> "My second post" 

2.1.1 :042 > post = Post.where(url: "www.google.com")
Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE "posts"."url" = 'www.google.com'
=> #<ActiveRecord::Relation [#<Post id: 1, title: "My first post", url: "www.google.com",        
description: "I sure hop this works">]> 
2.1.1 :043 > post.title
NoMethodError: undefined method `title'

使用post = Post.where(网址:“www.google.com”)时,我无法获得头衔。 有谁知道为什么?

1 个答案:

答案 0 :(得分:8)

Post.find(2)

返回单个实例

Post.where(...)

返回一个数组,或者更确切地说是一个ActiveRecord :: Relation对象。那里没有title方法。

试试这个

posts = Post.where(...)
posts.each { |post| p post.title }