Dav*_*hes 10 activerecord ruby-on-rails
假设我正在抽象代码,并且循环遍历对象x的列名,那么检测列是否为关联的最佳方法是什么?
我知道我可以做到这一点,但我想知道是否有更好的方法:
@user = User.first
@user.attributes.keys.each do |column|
if column[-3..-1] == "_id" && @user.respond_to?(column[0..-4].to_sym)
puts "#{column} is an association / relation."
else
puts "#{column} is not an assocation / relation."
end
end
end
Run Code Online (Sandbox Code Playgroud)
任何内置的Rails方法或助手来检测关联?上面的代码既不漂亮,也不是万无一失.谢谢!
Rya*_*igg 18
一种方法是反思该类的所有关联:
associations = class_goes_here.reflect_on_all_associations
Run Code Online (Sandbox Code Playgroud)
然后找到belongs_to
那些,因为那些将有_id
领域:
associations = associations.select { |a| a.macro == :belongs_to }
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过执行以下操作找到在这些关联上使用的外键:
association_foreign_keys = associations.map(&:foreign_key)
Run Code Online (Sandbox Code Playgroud)
我不会@user.attributes
用来获取属性,然后keys
用它来获取列名.我会User.column_names
用来获取列名.
因此,通过所有解释,您可以将代码更改为此以使其更加万无一失:
associations = User.reflect_on_all_associations
associations = associations.select { |a| a.macro == :belongs_to }
association_foreign_keys = associations.map(&:foreign_key)
User.column_names.each do |column|
if association_foreign_keys.include?(column)
puts "#{column} is an association / relation."
else
puts "#{column} is not an assocation / relation."
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1961 次 |
最近记录: |