craig
craig

Reputation: 26262

Rails 4 self-join adding where method to has_many causes errors

I would like to create a self-join that includes a where method filter.

To do so, I added , -> { where location_type: 'Hospital' } to the Model:

class Location < ActiveRecord::Base

  has_many :hospitals, class_name: "Location", foreign_key: "parent_id", -> { where location_type: 'Hospital' }
  belongs_to :system, class_name: "Location", foreign_key: "parent_id"

end

Unfortunately, this generates an error in the Rails Console:

2.0.0-p0 :001 > x = Location.find_by_id(1353)
SyntaxError: /Users/craibuc/Dropbox/Projects/Rails4/emr/app/models/location.rb:3: syntax error, unexpected '\n', expecting =>
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:423:in `load'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:423:in `block in load_file'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:615:in `new_constants_in'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:422:in `load_file'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:323:in `require_or_load'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:462:in `load_missing_constant'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:183:in `const_missing'
    from (irb):1
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
    from /Users/craibuc/.rvm/gems/ruby-2.0.0-p0/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

The documentation indicates that a where clause is support for a has_many, perhaps it isn't supported for self-joins. Can anyone confirm this? Is there another approach?

Upvotes: 0

Views: 407

Answers (1)

vee
vee

Reputation: 38645

Please note that lambda scope need to be specified before any other options supplied to the association declaration.

Please try:

has_many :hospitals, -> { where location_type: 'Hospital' }, class_name: "Location", foreign_key: "parent_id"

Upvotes: 1

Related Questions