The difference between search and relationship

I would not think that there is a difference when it comes to active recording and data retrieval.

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 

He gives me all the shows for this 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 see is, maybe I'm doing something wrong, because there is some difference between where to find it.

Any help is appreciated.

+6
ruby-on-rails activerecord ruby-on-rails-3
source share
3 answers

The problem is not related.

  u = User.find(1) 

one user returns

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

Result Type - ActiveRecord :: Relation → [User, User, User]

use for example. first to get the first user

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

u.class.name => "User"

+10
source share

User.find (1) retrieves a specific record with its identifier, while User.where ("username =?", "Percent20") retrieves a set of records that match the condition.

Try:

 u = User.where("username = ?", "percent20").first u.shows 
+5
source share

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

 u.each { |user| user.shows } 
+3
source share

All Articles