0

How to use joins or other ways to let me use the where query to compare other conditions in another model?

Model relation

class SonyAlarmLog < ActiveRecord::Base
  belongs_to :sony_alarm_test

class SonyAlarmTest < ActiveRecord::Base
  has_many :sony_alarm_bugs, :dependent => :destroy

It works, but returns me the columns of the SonyAlarmTest, I wanna the columns of sony_alarm_logs

SonyAlarmTest.joins{:sony_alarm_logs}
.where{ sony_alarm_logs.name =~ event_name }

It failed, get the ActiveRecord::ConfigurationError: Association named 'sony_alarm_tests' was not found on SonyAlarmLog; perhaps you misspelled it? Error

SonyAlarmLog.joins(:sony_alarm_tests)
.where{ name =~ event_name }

UPDATE (Fix: it should use the singular name)

But still got ActiveModel::MissingAttributeError: missing attribute: firmware_version error

I thought it may be mis-use of squeel syntax ?

SonyAlarmLog.joins(:sony_alarm_test)
.where{ name =~ event_name }
.where{ utc_time.gt (my{utc_time} + TIME_CORRECTION) }
.where{ sony_alarm_tests.round.eq(my{sony_alarm_test.round}) }
.where{ sony_alarm_tests.ip =~ my{sony_alarm_test.ip} }                            
.where{ sony_alarm_tests.firmware_version =~ my{sony_alarm_test.firmware_version} }
user3675188
  • 7,271
  • 11
  • 40
  • 76
  • Try with singular `SonyAlarmLog`, because that is your model name, not the pluralized `SonyAlarmLogs`. – vee Jun 27 '14 at 03:38
  • @vee sorry for the typos, I corrected it. – user3675188 Jun 27 '14 at 03:42
  • The `:sony_alarm_tests` in your `joins` also needs to be singular `:sony_alarm_test` which is the `belongs_to :sony_alarm_test` in your `SonyAlarmLog` model. – vee Jun 27 '14 at 03:43
  • @vee Thanks for your help, do you know how to use the where clause with joins – user3675188 Jun 27 '14 at 03:49
  • Please see my answer below. There needed to be a few changes in the syntax (basing this on the linked documentation of squeel). – vee Jun 27 '14 at 04:04

1 Answers1

0

Following up to the comments... As per the documention of squeel, you could write your query as:

SonyAlarmLog.joins{:sony_alarm_test}.
  where{ 
    (name =~ event_name) & 
    (utc_time.gt (my{utc_time} + TIME_CORRECTION)) & 
    (sony_alarm_test.round.eq(my{sony_alarm_test.round})) &
    (sony_alarm_test.ip =~ my{sony_alarm_test.ip}) &                            
    (sony_alarm_test.firmware_version =~ my{sony_alarm_test.firmware_version})
  }

The reason you are getting the error is likely because of the either sony_alarm_tests.firmware_version or sony_alam_test.firmware_version. Note one of them is plural and the other one is singular. You want to be using "singular" version here as the association is "belongs_to".

vee
  • 38,255
  • 7
  • 74
  • 78