Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between find and Where with Relationships

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_many :shows
end

class Show < ActiveRecord::Base
  belongs_to :user
end

When I use the rails console I can do the following and it works.

u = User.find(1)
u.shows

It gives me all the shows for that user.

However when I do

u = User.where("username = ?", "percent20")
u.shows # this is doesn't work gives me a now instance error

I get the same user and relevant information, but not the relationship. The only problem I can see is maybe I am doing something wrong because there is some difference between where and find.

Any help is appreciated.

like image 657
Buddy Lindsey Avatar asked Mar 06 '11 20:03

Buddy Lindsey


2 Answers

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"

like image 60
mm1 Avatar answered Nov 14 '22 23:11

mm1


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
like image 28
clemensp Avatar answered Nov 14 '22 23:11

clemensp