开发者

AR Query returning a relation instead of the expected object type (model person)

Queries returnin开发者_JAVA技巧g different object types based on using limit() or first

This example uses limit(1) and does not produce the expected object type:

c =  PersonCategory.where("category = ?", "Crown").limit(1) ##
=> PersonCategory Load (0.3ms)  SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1
=> [#<PersonCategory id: 1, category: "Crown">]  #####
c.class
=> ActiveRecord::Relation 

This example uses first and gives the desired output:

c =  PersonCategory.where("category = ?", "Crown").first ##
=> PersonCategory Load (0.4ms)  SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1
=> #<PersonCategory id: 1, category: "Crown"> 
c.class
=> PersonCategory(id: integer, category: string)   #####
ruby-1.9.2-p180 :034 > 


limit returns a limited set of results. In your case, it returns what is essentially an array of PersonCategory objects, even if you only specify one object with limit(1).

For instance, calling PersonCategory.limit(15) would return the first 15 PersonCategory items in your database.

first, on the other hand, only returns the first result of it's preceding query - not an array of results. That's why you would see an individual PersonCategory object being returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜