Friday, 15 March 2013

sql - Retrieve a list of polymorphic relations in Rails 4 -



sql - Retrieve a list of polymorphic relations in Rails 4 -

i have rails4 app next models:

1. systems (has many devices, has many parameters through devices) 2. devices (belongs system, has many parameters) 3. parameters (belongs device) 4. events (polymorphic - systems, devices , parameters can have events)

when event created, boolean field (on event) assigned value. false indicated failure.

i have scope on events, show failing events:

scope :failing, -> { where(okay: false).order('created_at desc') }

i can retrieve events follows:

system.events.failing device.events.failing parameter.events.failing

i trying homecoming list of systems either:

1. recent event scheme has failed 2. recent event of it's devices has failed 3. recent event parameters of it's devices have failed

i have written (horrible) sql query when executed in console, returns systems array:

"select * systems systems.id in (select devices.system_id devices devices.id in (select parameters.device_id parameters bring together events on parameters.id=events.eventable_id events.okay ='f')) or systems.id in (select devices.system_id devices bring together events on devices.id=events.eventable_id events.okay='f')")

i need either define scope on scheme model or class method homecoming list of 'failing' systems. can help?

you mix joins , merges (to merge clauses of scope):

class scheme # 1. recent event scheme has failed scope :with_failing_events, -> { joins(:events).merge event.failing } # 2. recent event of it's devices has failed scope :with_failing_devices, -> { joins(devices: :events).merge event.failing } # 3. recent event parameters of it's devices have failed scope :with_failing_parameters, -> { joins(devices: { parameters: :events }).merge event.failing } end

notice passing hash joins enables multiple join, or @ to the lowest degree seems work in app i'm working @ (rails 4.0.5 postgresql).

to filter latest event (warning not work in postgres, untested on other adapters), append queries:

system.joins(:events).merge(event.failing).where events: { updated_at: 'max("events"."updated_at")' }

in case, can merge these scopes or this:

class scheme scope :failing, -> where( [ with_failing_events, with_failing_devices, with_failing_parameters ].map(&:where_clauses).join(' or ') ) end end

sql ruby-on-rails ruby activerecord scope

No comments:

Post a Comment