重用where查询的更好做法是什么

时间:2014-06-27 05:23:22

标签: ruby-on-rails activerecord

如何在2种方法中重复使用相同的查询?

.where(sony_alarm_tests: {ip: sony_alarm_test.ip})
.where(sony_alarm_tests: {round: sony_alarm_test.round})
.where(sony_alarm_tests: {firmware_version: sony_alarm_test.firmware_version})

问题在于我的查询取决于.joins(:sony_alarm_test)

我不知道?感谢

  def previous(event_name=self.name)
    SonyAlarmLog.joins(:sony_alarm_test)
    .where{ utc_time.lt (my{self.utc_time} - TIME_CORRECTION) }
    .where{ name =~ event_name }
    .where(sony_alarm_tests: {ip: sony_alarm_test.ip})
    .where(sony_alarm_tests: {round: sony_alarm_test.round})
    .where(sony_alarm_tests: {firmware_version: sony_alarm_test.firmware_version})
  end

  def following(event_name=self.name)    
    SonyAlarmLog.joins(:sony_alarm_test)
    .where{ name =~ event_name }
    .where{ utc_time.gt (my{utc_time} + TIME_CORRECTION) }
    .where(sony_alarm_tests: {ip: sony_alarm_test.ip})
    .where(sony_alarm_tests: {round: sony_alarm_test.round})
    .where(sony_alarm_tests: {firmware_version: sony_alarm_test.firmware_version})
  end

1 个答案:

答案 0 :(得分:0)

您可以为此创建范围。

我已将http://guides.rubyonrails.org/active_record_querying.html的以下内容作为您的解释国

作用域允许您指定常用查询,这些查询可以作为关联对象或模型上的方法调用引用。使用这些范围,您可以使用之前涵盖的每种方法,例如where,joins和includes。所有范围方法都将返回一个ActiveRecord :: Relation对象,该对象将允许在其上调用更多方法(例如其他范围)。

您可以创建这样的范围

class Post < ActiveRecord::Base
   scope :published, -> { where(published: true) }
end

要调用此已发布的范围,我们可以通过以下方式调用它

Post.published # => [published posts]

您可以参考http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/scope