我需要列出所有属于模型对象中的关联,并遍历它们.有办法做到这一点吗?

推荐答案

你可以利用这个类的reflections散列来完成这个任务.可能有更直接的方法,但这是可行的:

# say you have a class Thing
class Thing < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

# this would return a hash of all `belongs_to` reflections, in this case:
# { :foo => (the Foo Reflection), :bar => (the Bar Reflection) }
reflections = Thing.reflections.select do |association_name, reflection| 
  reflection.macro == :belongs_to
end

# And you could iterate over it, using the data in the reflection object, 
# or just the key.
#
# These should be equivalent:
thing = Thing.first
reflections.keys.map {|association_name| thing.send(association_name) }
reflections.values.map {|reflection| thing.send(reflection.name) }

Ruby-on-rails相关问答推荐

如何在rails 7中禁用Simple_Form验证

使用Rails和RSpec,有没有办法查看操作真正将您带到哪个页面?

Rails 7 中的预编译

如何在测试期间为 Rails 应用程序启用 Rails.cache 会话对象

为 has_attached_file 等活动记录属性创建类方法

使用rails form_for时带有_path的未定义方法

禁用冻结字符串文字注释判断

查找日期时间与今天匹配的记录 - Ruby on Rails

Ruby on Rails 的 varchar 迁移问题

将 defer 属性添加到 javascript_include_tag Rails

使用 ActiveRecord 3 / Arel 查找单个记录的最佳方法?

如何在 routes.rb 中使用 301 或 302 进行重定向

将根 url 重定向到 Rails 应用程序中的其他位置

Rails 文章助手 - a 或 an

我可以将默认值传递给 rails 生成迁移吗?

获取磁盘上 ActiveStorage 文件的路径

Rails,设计认证,CSRF 问题

如何检测导致 Rake 中的弃用警告的原因

从 Rails 中的 ActiveRecord::RecordNotFound 救援

如何在 rake 任务中强制 RAILS_ENV?