ruby-on-rails - Rails 如何查询关联定义

标签 ruby-on-rails ruby activerecord metaprogramming

我有很多动态代码将复杂的关系保存在一个字符串中。 例如:

 "product.country.continent.planet.galaxy.name"

如何检查这些关系是否存在? 我想要一个像下面这样的方法:

  raise "n00b" unless Product.has_associations?("product.country.planet.galaxy")

我该如何实现?

最佳答案

试试这个:

def has_associations?(assoc_str)
  klass = self.class
  assoc_str.split(".").all? do |name| 
    (klass = klass.reflect_on_association(name.to_sym).try(:klass)).present?
  end
end

关于ruby-on-rails - Rails 如何查询关联定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272478/

相关文章:

ruby-on-rails - 通过初始化程序向 ActiveRecord::Base 添加范围?

php - MySQL Codeigniter - $this->db->query 和 CLI 结果不匹配

sql - counter_cache has_many_through sql优化,减少sql查询次数

ruby - 从 Postgres 时间戳中添加或减去时间

android - 如何在自己的 shell 中从 Ruby 执行 shell 命令?

html - 如何使用 Nokogiri 解析 Wikipedia 中的深度嵌套文本?

php - Codeigniter 设置横向数据库过滤器

ruby-on-rails - 如何在Rails中建立多对多关系

python - Heroku 上的进程间通信

Javascript "if statement"和嵌入式 ruby​​(ruby 变量始终为 true)