views:

39

answers:

3

Hi,

Considering this:

@article = Article.first(:joins => :category)

Does ActiveRecord provides a generique method which return a array of any belongs to class name?

For example:

@article.name.parents # => ["category"]

Thanks

A: 

When you have a relation between two models, for example, an article having one category, you'll have a has_many relation in the category. And a belongs_to in the article.

class Article < ActiveRecord::Base
    belongs_to :category
end

class Category < ActiveRecord::Base
    has_many :articles
end

Then you can, from either an article or a category, retrieve the related object.

article.category # => The category
category.articles # => The articles

There's no "parent". Each model has their own relations. If you need to retrive one model's relations, you must define it in order to have access to it.

Damien MATHIEU
Thank you for your answer. A agree with you. But I would like to use a generic method to do so. If for example Article belongs to Category and Magazine, I would like to provide this:@article.name.parents # => ["Category", "Magazine"]But Article.parents method do not returns every belongs_to classes, and after testing some other methods such as:@article.belongs_toI get an error (because belongs_to require an argument) or an other information. And after searching by trying this:@article.class.methods.each { |method| begin @article.class.send(method) rescue true end }I get an error.
Denis
A: 

I believe this is not possible, cause what Rails is doing when having belongs_to :something inside some class, is a meta programming technique to add a method def something inside that class and it doesn't really store those 'parent' classes.

khelll
A: 

To find all the "belongs_to" associations for your model, those of which are "parents" you can do this:

YourModel.reflections.select { |name, reflection| reflection.macro == :belongs_to }
Ryan Bigg
Awesome idea! Many Thanks. I just add some other methods and it's okay: Article.reflections.select { |name, reflection| reflection.macro == :belongs_to }.collect { |table| table[0].to_s.classify }
Denis