0

I have an active record class that looks like

class User < ApplicationRecord
  has_many :audiobooks
  has_many :ebooks
  has_many :physicalbooks
end

I want to get/set the relations using the names. How can I do that?

A probable example of the operation I want to perform:

books =  [ :audiobooks, :ebooks, physicalbooks] 
books.each do |b|
  user[b].build(...)
end

How can I do this in ActiveRecord.

sheki
  • 8,991
  • 13
  • 50
  • 69

1 Answers1

2

You can use send method, like so:

user.send(b)
Gerry
  • 10,337
  • 3
  • 31
  • 40
m3characters
  • 2,240
  • 2
  • 14
  • 18