Z
Z
zggb2015-02-15 20:34:20
Ruby on Rails
zggb, 2015-02-15 20:34:20

Active Record, scope and nesting of the third level?

Hello!
There is a User model . It contains the Estate
has_many :estates, dependent: :destroy
Model . It has a polymorphic relationship

has_one :location, as: :locatable, dependent: :destroy

I want to filter User by location
Simple attachments filtered by scope, by type
scope :type, -> (type) { User.includes(:estates).where("estates.re_type" => type) }

I can't figure out how to get through User to Location.
Thank you in advance!
UPD Migrating Location
class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|
      t.string :address
      t.decimal :lat, {:precision=>10, :scale=>6}
      t.decimal :lng, {:precision=>10, :scale=>6}
      t.references :locatable, polymorphic: true, index: true

      t.timestamps null: false
    end
    add_index  :locations, [:lat, :lng]
  end
end

UPD
Tried
1)
User.where(estates: { location: { name: "there" } })

Mistake
SQLite3::SQLException: no such column: real_estates.locatable_id: SELECT "users".* FROM "users" WHERE "real_estates"."locatable_id" = '---
:address: !ruby/object:Arel::Nodes::BindParam {}'

2)
User.joins(estates: :location).where(location: {address: "London"})

Mistake
SQLite3::SQLException: no such column: location.address: SELECT "users".* FROM "users" INNER JOIN "estates" ON "estates"."user_id" = "users"."id" INNER JOIN "locations" ON "locations"."locatable_id" = "estates"."id" AND "locations"."locatable_type" = ? WHERE "location"."address" = 'London'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zggb, 2015-02-17
@zggb

User.joins(estates: :location).where(locations: {address: "London"})

V
Viktor Vsk, 2015-02-15
@viktorvsk

First, try a hash entry, like

User.where(estates: { location: { name: "there" } })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question