Game.On
Game.On

Reputation: 95

Accessing one element in a has many relationship

I have two classes with one-to-many relationship. For example:

class User 
  has_many :numbers
  ...
end

How can I access one individual number that user has without using for or each? I tried user.numbers[2] and it didn't work (I was thinking it's like using a basic array but apparently it's not).

Upvotes: 0

Views: 533

Answers (1)

Kyle C
Kyle C

Reputation: 4097

First find the user

user = User.find(1) or user = User.first
user.numbers.first   #this will return the first associated object

Upvotes: 4

Related Questions