john mitsch
john mitsch

Reputation: 171

Rails - Get the name from a has_many => through association as a string

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 model Baz I would like to get the has_many name as a string. In this example it is "other_mars"

The solution would have to work for any similar has_many relationship with a class_name passed to it.

I am using Rails 3.2 and ruby 1.9

Upvotes: 3

Views: 949

Answers (2)

Venkat Ch
Venkat Ch

Reputation: 1268

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 results ['other_mars']. i.e it returns all the associations declared with the :class_name key.

Upvotes: 1

Cyzanfar
Cyzanfar

Reputation: 7146

I would like to get the has_many name as a string. In this example it is "other_mars"

If what you are looking for is the related association for a model, in your case Baz open up your rails console in the project directory and type:

Baz.reflect_on_all_associations(:has_many)

This will return an ActiveRecord object with the a list of the associations under the attribute @name.

So the name of the association to a string can be obtained by typing

Baz.reflect_on_all_associations(:has_many).name.to_s

Upvotes: 1

Related Questions