3

在 ActiveRecord 中,has_many 关系使用外键列来加载关联。所以:

class Person < ActiveRecord::Base
  has_many :messages
end

class Messages < ActiveRecord::Base
  belongs_to :person
end

Person.limit(10).includes(:messages) 
# select * from persons limit 10;
# select messages.* from messages where person_id in (1, 2, 3...)

我有一个案例(我也看到其他人也要求这样做),我不希望 Rails 自动将外键检查附加到 where 子句。相反,我可能想要类似的东西:

class Person < ActiveRecord::Base
  has_many :messages, 
           :foreign_key => false, 
           :conditions => proc { ["person_id is null or person_id = ?", self.id] }
end

Person.limit(10).includes(:messages)
# select messages.* from messages where person_id is null or person_id in (1, 2, 3...)

我怎样才能做到这一点?总而言之,我不希望 ActiveRecord 自动在 WHERE 子句中附加外键,我希望能够指定它用于关联的表达式。

我不想这样做:

class Person < ActiveRecord::Base
  def messages
    Message.where("person_id is null or person_id = #{ self.id }")
  end
end

据我所知,这会破坏急切的加载。

我也不想使用finder_sqlhas_many 的选项,因为这会破坏person.messages.where(:id => 1)Person.limit(10).includes(:messages => :image)

4

1 回答 1

1

像这样的东西在 Rails 3.2.1 上对我有用:

class Person < ActiveRecord::Base
  has_many :messages, :finder_sql => lambda{ "SELECT * FROM messages WHERE messages.person_id=#{id} OR messages.person_id IS NULL" }
end

# person = Person.includes(:messages).first
# person.messages.loaded?  #=> true
于 2012-09-07T19:35:20.010 回答