I also want to find the association name dynamically from a dynamic
object. I was looking for something to help me on this. '
ActiveRecord::Reflection' a nice module to get association info.

Thanks Peter.
- Abhi




Peter wrote in post #1032176:
On Nov 15, 12:27pm, PandaR1 wrote:
belongs_to :currency, :class_name => "Measureunit" , :foreign_key =>
"currency_id"

How can I recover the class name from the association name (eg. I have the
string 'Currency' and I look for
a method that return 'Measureunit')

I found class_name() and klass() but I can't figure the syntax...
I believe what you're saying is that you have the Vendor class, and
the name of the association as a string, 'Currency'. You want to look
at The ActiveRecord::Reflection documentation, specifically
reflect_on_association (http://apidock.com/rails/ActiveRecord/
Reflection/ClassMethods/reflect_on_association). That gives you back
an AssociationReflection, which has a bunch of information for you:
http://apidock.com/rails/ActiveRecord/Reflection/AssociationReflection.
Specifically again, you likely want klass on that, which should return
the class of the association; do be aware that its a little bit more
complex for polymorphic relationships if that's necessary to support.

So in summary what you likely want is something like
s = "Currency"
association_name = s.underscore # Or
whatever transformation takes your string to your association name
reflection = Vendor.reflect_on_association(association_name) #
Returns the AssociationReflection object
reflection.klass #
Returns the class object, in this case Measureunit

HTH,
\Peter
--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/27b8fe84844d4d2c5e31a023fcaa314b%40ruby-forum.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 4 of 4 | next ›
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedNov 16, '11 at 8:31a
activeJun 13, '16 at 6:01a
posts4
users4
websiterubyonrails.org
irc#RubyOnRails

People

Translate

site design / logo © 2021 Grokbase