Difference Between find and Where with Relationships

前端 未结 3 1768
清歌不尽
清歌不尽 2021-01-05 17:51

I wouldn\'t think there is a difference when it comes to active record and finding data.

Here are my models

class User < ActiveRecord::Base
  has_         


        
3条回答
  •  失恋的感觉
    2021-01-05 18:13

    The problem is not the relationship.

     u = User.find(1) 
    

    returns one User

     #return a Set of users. In your case its only one user.
     u = User.where("username = ?", "percent20") 
    

    The result type is ActiveRecord::Relation --> [User, User, User]

    use e.g. first to get the first User

     #returns the first user
     u = User.where("username = ?", "percent20").first
    

    u.class.name => "User"

提交回复
热议问题