【问题标题】:How to display all association collection in rails console?如何在 Rails 控制台中显示所有关联集合?
【发布时间】:2021-10-16 20:17:45
【问题描述】:

我想在 Rails 控制台中显示父实体“Article”的所有集合,这将是自身之间的关系,例如:

# 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

现在我拥有的是:

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

我想在 Rails 控制台上显示的内容:

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: []
  ]

]

我最终要寻找的是是否咨询父母以展示他们的孩子(如果可能的话,还有孩子的孩子)

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rubygems rails-console


    【解决方案1】:

    这可能最好通过在顶级文章上调用to_json,并配置Articleas_json 方法来包含sub_articles 来实现

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

    在 Rails 控制台中:

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

    【讨论】:

    • 非常感谢,这就是我一直在寻找的,能够连续注入实体的孩子的方法
    • @SamuelDaCosta 如果满足您的需要,请将其指定为可接受的答案
    猜你喜欢
    • 1970-01-01
    • 2015-11-07
    • 2017-06-11
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多