默认情况下,我可以使belongs_to关联使用预先加载吗?

时间:2015-04-20 04:29:04

标签: ruby-on-rails-4 eager-loading belongs-to

我正在连接到我公司的一个SQL Server数据库,并尝试设置ActiveRecord,因此我可以将它们视为与Rails对象相同。

我有这两个模型:

class Change < ActiveRecord::Base
  belongs_to :affected_contact, class_name: "Contact"
end

class Contact
  # Contact's primary key is a binary UUID; I can't change this
end

我正试图让受影响的人接触到一个特定的变化。通常情况下,这只是一个简单的案例,但是:

Change.first.affected_contact
  Change Load (52.6ms)  EXEC sp_executesql N'SELECT TOP (1) [chg].* FROM [chg] ORDER BY [chg].[id] ASC'
  Contact Load (28.0ms)  EXEC sp_executesql N'SELECT TOP (1) [ca_contact].* FROM [ca_contact] WHERE [ca_contact].[contact_uuid] = @0', N'@0 binary', @0 = 0xfcf9a8ac6381aa4386c9b10ee382e10b  [["contact_uuid", "<16 bytes of binary data>"]]
=> nil

......那不是我想要的!然而,如果我首先加入加入,它就会起作用:

Change.eager_load(:affected_contact).first.affected_contact
  SQL (34.4ms)  EXEC sp_executesql N'SELECT TOP (1) holy_crap_theres_a_lot_of_columns FROM [chg] LEFT OUTER JOIN [ca_contact] ON [ca_contact].[contact_uuid] = [chg].[affected_contact] ORDER BY [chg].[id] ASC'
=> #<Contact contact_uuid: "\xFC\xF9\xA8\xACc\x81\xAAC\x86\xC9\xB1\x0E\xE3\x82\xE1\v", ... >

事实上,如果我以任何方式强制匹配发生在JOIN子句中,它将起作用,但belongs_to似乎使用WHERE子句,而nil 1}}是我能得到的最佳响应(很多时候,字符串及其二进制类型之间存在转换错误)。

有没有办法确保在JOIN关联上默认发生belongs_to子句的急切加载?

2 个答案:

答案 0 :(得分:0)

我发现#find_by_contact_uuidcontact_uuid是主键)工作,#find没有,因为某些原因。这导致了这一点的实施。

我最终基本上重写了Active Record提供的关联方法:

module AssociationMethods
  def self.included(base)
    base.reflect_on_all_associations(:belong_to).each do |a|
      define_method a.name do
        # #find_by_<uuid_pk> seems to work where #find doesn't
        a.klass.send "find_by_#{a.association_primary_key}", self[a.foreign_key]
      end
    end

    base.reflect_on_all_associations(:has_many).each do |a|
      define_method a.name do
        a.klass.where(a.foreign_key => self.send(a.association_primary_key))
      end
    end
  end
end

class Contact
  has_many :changes, foreign_key: :affected_contact_id
  include AssociationMethods # include *after* all associations are defined
end

class Change
  belongs_to :affected_contact, class_name: 'Contact'
  include AssociationMethods
end

它不包括Active Record在设置关联时提供的所有,但它似乎可以解决问题。

答案 1 :(得分:-1)

使用includes可以解决您的问题。这是因为includespreloadeager_load取决于您的其他条件。

read more here

相关问题