gpt4 book ai didi

ruby-on-rails - rails 方法获取模型的关联名称

转载 作者:行者123 更新时间:2023-12-03 08:34:52 25 4
gpt4 key购买 nike

有没有办法找出模型有哪些关联?拿这两个模型:

class Comment < ActiveRecord::Base
belongs_to :commentable
end

class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
end

我正在寻找类似的东西:
Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']

最佳答案

您正在寻找 reflect_on_all_associations .

简而言之:

Post.reflect_on_all_associations(:has_many)

...将给出所有 name 的数组(具有 has_many 等属性的对象)协会。

关于ruby-on-rails - rails 方法获取模型的关联名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2024205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com