Bazley
Bazley

Reputation: 2847

Ruby on Rails has_many -- creating associations for individual records

Here is my model:

class User < ActiveRecord::Base
  has_many :dogs
end

The number of dogs is small however, and I want to be able to refer to each one by an individual name. I want to have something like this in the end:

@barry = new User(name: 'Barry')
@barry.rover
@barry.patch.weight

How do you achieve this?

Upvotes: 0

Views: 49

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

I honestly don't think it's a good idea, but you could try something like this:

def method_missing(name, *args, &block)
  dogs.find_by(name: name) or super(name, *args, &block)
end

But it will not create an association for you.

The code above is written with assumption Dog model has name attribute. Now you're able to do:

barry = User.create(name: 'Barry')
barry.dogs.create(name: 'rover', weight: 12)
barry.dogs.create(name: 'patch', weight: 8)
barry.rover        #=> #<Node name: 'rover' weight: 12>
barry.patch.weight #=> 8
barry.other        #=> error

Upvotes: 1

Related Questions