user938363
user938363

Reputation: 10360

How to declear association from an array in Rails 4 model?

We would like to do something like following in a user model:

class User < ActiveRecord::Base
  model_names = ['Pets', 'Computers' ]
  model_names.each do |a|
    has_many #{a.to_sym}
  end 
end

Is the code above going to work in Rails 4? Or any better way to do that?

Upvotes: 0

Views: 35

Answers (1)

Taryn East
Taryn East

Reputation: 27747

Yes you can do that, but rails expects those names to be lowercase, snake-case symbols instead of class names.

You can try tableize for that

If you need them to be classnames, you'll need to do something like:

 model_names.each do |a|
   has_many a.tableize.to_sym
 end 

Though TBH I'd go the other way eg:

class User < ActiveRecord::Base
  model_names = [:pets, :computers ]
  model_names.each do |a|
    has_many a
  end 
end

then if you ever needed to use model_names elsewhere use: model_names.map{|a| a.classify } with possibly constantize to turn it into a real class.

Upvotes: 1

Related Questions