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.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With