如何动态生成关联名称? [英] How to dynamically generate association names?

查看:43
本文介绍了如何动态生成关联名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby on Rails 3.2.2 和 Squeel gem.我有以下语句,我正在尝试在 Mixin 模块 中重构 my_squeel_query 方法(因为它被我的许多模型使用):

I am using Ruby on Rails 3.2.2 and the Squeel gem. I have following statements and I am trying to refactoring the my_squeel_query method in a Mixin module (since it is used by many of my models):

# Note: 'article_comment_associations' and 'model_as_like_article_comment_associations'
# refer to database table names.

class Article < ActiveRecord::Base
  def my_squeel_query
    commenters.
      .where{
        article_comment_associations.article_id.eq(my{self.id}) & ...
      }
  end
end

class ModelAsLikeArticle < ActiveRecord::Base
  def my_squeel_query
    commenters.
      .where{
        model_as_like_article_comment_associations.article_id.eq(my{self.id}) & ...
      }
  end
end

我的问题是我可以不能通过在 Mixin 模块中生成动态名称来重构 article_comment_associationsmodel_as_like_article_comment_associations 语句.也就是说,如果这是一个 String 我可以通过使用类似 "#{self.class.to_s.singularize}_comment_associations" 的东西动态生成相关名称,如下所示:

My problem is that I can not refactoring article_comment_associations and model_as_like_article_comment_associations statements by generating a dynamic name in the Mixin module. That is, if that was a String I could dynamically generate the related name by using something like "#{self.class.to_s.singularize}_comment_associations" as the following:

class Article < ActiveRecord::Base
  include MyModule
end

class ModelAsLikeArticle < ActiveRecord::Base
  include MyModule
end

module MyModule
  def my_squeel_query
    commenters.
      .where{
        # Note: This code doesn't work. It is just an sample.
        "#{self.class.to_s.singularize}_comment_associations".article_id.eq(my{self.id}) & ...
      }
  end
end

但是,由于这不是我的情况,我无法构建"名称并使 my_squeel_query 跨模型共享".

But, since it is not my case, I cannot "build" the name and make the my_squeel_query to be "shared" across models.

如何动态生成与 Squeel gem 相关的关联名称?我应该考虑以另一种方式重构吗?你有什么建议?

How can I dynamically generate association names related to the Squeel gem? Should I think to refactoring in another way? What do you advice about?

推荐答案

由于 DSL 是 instance_evaled,你实际上可以这样说:

Since the DSL is instance_evaled, you can actually say something like:

def my_squeel_query
  base = self
  commenters.
    .where{
      # Note: This code does work. Because it's awesome.
      __send__("#{base.class.to_s.singularize}_comment_associations").
        article_id.eq(my{self.id})
    }
end

这篇关于如何动态生成关联名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆