Difference Between find and Where with Relationships

前端 未结 3 1749
清歌不尽
清歌不尽 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:10

    The where is method that returns an array of objects. So, in your case try

    u.each { |user| user.shows }
    
    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2021-01-05 18:18

    User.find(1) is retrieving a specific record with its ID, whereas User.where("username = ?", "percent20") is retrieving the set of records that match the condition.

    Try:

    u = User.where("username = ?", "percent20").first
    u.shows
    
    0 讨论(0)
提交回复
热议问题