How to declear association from an array in Rails 4 model? -
we following in user model:
class user < activerecord::base model_names = ['pets', 'computers' ] model_names.each |a| has_many #{a.to_sym} end end
is code above going work in rails 4? or better way that. thanks.
yes can that, rails expects names lowercase, snake-case symbols instead of class names.
you can try tableize that
if need them classnames, you'll need like:
model_names.each |a| has_many a.tableize.to_sym end
though tbh i'd go other way eg:
class user < activerecord::base model_names = [:pets, :computers ] model_names.each |a| has_many end end
then if ever needed use model_names elsewhere use: model_names.map{|a| a.classify }
possibly constantize
turn real class.
Comments
Post a Comment