【问题标题】:Rails ActiveRecord has_one and belongs_to reloading associationRails ActiveRecord has_one 和 belongs_to 重新加载关联
【发布时间】:2014-03-14 15:29:52
【问题描述】:

我有四个模型

class Votation
  belongs_to :quorum

  def calc
    return self.quorum.calc
  end

end

class Quorum
  has_one :votation
  ...
end

class NewQuorum < Quorum
  def calc
    do stuff and call
    self.votation.attribute_a
  end
end

class OldQuorum < Quorum
  def calc
    do stuff and call
    self.votation.attribute_b
  end
end

我已将投票加载到 @votation 对象中,并急切地加载了关联的 Quorum。

问题是,当我调用@votation.calc 时,ActiveRecord 执行 SQL 选择以再次加载投票,例如,当它必须执行 self.votation.attribute_a 时。

SELECT "votations".* FROM "votations" WHERE "votations"."quorum_id" = $1

我怎样才能避免这个选择被执行?

【问题讨论】:

    标签: ruby-on-rails activerecord belongs-to has-one


    【解决方案1】:

    您可以在指定关联时使用:inverse_of 选项来防止另一个选择语句被执行。

    所以你的模型看起来像:

     class Votation
       belongs_to :quorum, inverse_of: :votation
     end
    
     class Quorum
       has_one :votation, inverse_of: :quorum
     end
    

    参考:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 2012-12-09
      相关资源
      最近更新 更多