ruby-on-railsrubyactiverecordrubygemsrails-console

How to display all association collection in rails console?


I'd like to display in rails console all the collections of the parent entity "Article", which would be a relationship between itself, example:

# article.rb

class Article < ActiveRecord::Base
 belongs_to :parent, :class_name => 'Article', optional: true
 has_many :sub_articles, :class_name => 'Article', :foreign_key => 'parent_id'
end

Now what I have is:

irb(main):095:0> Article.find(1)
Article Load (0.9ms)  SELECT "articles".* FROM "articles" ORDER BY 
"articles"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> 
#<Articles:0x0000264231faa292

id: 1,
name: "king article"
created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
parent_id: nil

What I'd like to display on the rails console:

id: 1,
name: "king article"
created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
parent_id: nil
sub_articles:

[ Article:0x0000641428defb71
id: 2,
  name: "pencils article"
  created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
  updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
  parent_id: 1
  sub_articles:
    [ Article:0x0000621438defb71
    id: 3,
    name: "pencil child 1"
    created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    parent_id: 2
    sub_articles: [],

    id: 4,
    name: "pencil child 2"
    created_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    updated_at: Fri, 13 Aug 2021 13:14:26.463429000 UTC +00:00,
    parent_id: 2
    sub_articles: []
  ]

]

Ultimately what I am looking for is if a parent is consulted to show their children (and the children of the children if possible)


Solution

  • It's probably best achieved by calling to_json on the top-level article, and configuring the as_json method of Article to include sub_articles

    class Article < ActiveRecord::Base
      def as_json(options={})
        super(methods: [:subarticles])
      end
    end
    

    in the rails console:

    $> Article.find(3).to_json # => should give you the hierarchy you're looking for