Rails - get name from has_many => via string concatenation
I have three models
class Mar < ActiveRecord::Base
belongs_to :baz
belongs_to :koo
end
class Baz < ActiveRecord::Base
has_many :other_mars, :class_name => "Mar", :foreign_key => :b
end
class Koo < ActiveRecord::Base
has_many :mars
has_many :bazs, :through => :mars, :source => :baz
end
and from the Baz model I would like to get the has_many name as a string. In this example, this is "other_mars"
The solution should work for any similar has_many relationship with the class_name passed to it.
I am using Rails 3.2 and ruby 1.9
source to share
If I understand your requirement correctly, the following code helps
result = Baz.reflect_on_all_associations.collect do |association|
association.name.to_s if association.options[:class_name].present?
end.compact
In your case, the above code shows ['other_mars']
. that is, it returns everything associations
declared with a key :class_name
.
source to share
I would like to get the has_many name as a string. In this example, this is "other_mars"
If you need an appropriate association for the model, in your case Baz
open the rails console in the project directory and type:
Baz.reflect_on_all_associations(:has_many)
This will return an ActiveRecord object with a list of associations under the attribute @name
.
So, the association name for a string can be obtained by typing
Baz.reflect_on_all_associations(:has_many).name.to_s
source to share