ruby on rails - What's the better practice to reuse the where query -


how reuse same queries in 2 methods ?

.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}) 

the trouble me queries depends on .joins(:sony_alarm_test).

i have no idea ? thanks

  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 

you can create scope this.

i have taken following content http://guides.rubyonrails.org/active_record_querying.html explain-nation

scoping allows specify commonly-used queries can referenced method calls on association objects or models. these scopes, can use every method covered such where, joins , includes. scope methods return activerecord::relation object allow further methods (such other scopes) called on it.

you can create scope

class post < activerecord::base    scope :published, -> { where(published: true) } end 

to call published scope can call following way

post.published # => [published posts] 

you can refer http://apidock.com/rails/activerecord/namedscope/classmethods/scope


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -