【问题标题】:many belongs_to and has_many in single line单行中的许多 belongs_to 和 has_many
【发布时间】:2014-11-18 11:08:21
【问题描述】:

您好,我正在开发一个与模型有很多关系的应用程序。 现在我正在考虑减少代码行,我发现了很多关系,比如has_manybelongs_to

我们可以有一个单行,我们可以写类似的东西

belongs_to [:comment, :rating, :indication], dependent: :destroy

belongs_to :travels, foreign_key: travel_item_id

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4.1


    【解决方案1】:

    不幸的是,没有。 AFAIK 这是不可能的,甚至文档似乎也不允许这样做。 您可以做的是定义一个迭代数组并创建此关联的元编程方法。但不确定是否值得。

    编辑

    这只是我所说的metaprogramming method 的一个例子 创建文件app/models/concerns/associate.rb

    module Associate
      extend ActiveSupport::Concern
    
      module ClassMethods
        def associate(ass_type, names = [], params = {})
          names.each do |n|
            send ass_type, n, params
          end
        end
      end
    end
    

    然后,在你的模型中,做多个belongs_to,就做

    include Associate
    associate :belongs_to, [:comment, :rating, :indication], dependent: :destroy
    

    【讨论】:

    • 是的。当您说元编程时,这正是我所做的。非常感谢您的详细回答。这对我很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多