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
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
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.
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.
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 }