Reputation: 1458
I am trying to view nested records from the rails console.
I have subarticles nested into articles. In other words, subarticles belongs to article, and articles has many subarticles.
I have tried something like Article.subarticle.all
from the console but this doesn't work.
What is the best way to go about this?
Upvotes: 0
Views: 326
Reputation: 52357
I think joins
is what you are looking for:
Article.joins(:subarticles)
will generate following SQL:
SELECT "articles".* FROM "articles" INNER JOIN "subarticles" ON "subarticles"."article_id" = "article"."id"
Another option is to simply map
all articles by its subarticles:
Article.all.map(&:subarticles)
It will return a relation with all subarticles where article_id
is not null.
Upvotes: 3
Reputation: 286
To be able to call Article.subarticle.all
, you need to define an association in Article model.
class Article < ActiveRecord::Base
has_many :subarticles
...
end
Reference: http://guides.rubyonrails.org/association_basics.html
Upvotes: 0
Reputation: 375
If you want to view all subarticles
to one particular Article
, you just need to assign it to a variable:
a = Article.find(1)
- this will assign Article with id = 1
And then call:
a.subarticles
- this will show all subarticles
associated with your Article
Upvotes: 4