2013-08-27 34 views
0

我想創建一個包含where方法過濾器的自連接。Rails 4自我加入添加has_many的方法會導致錯誤的方法

要做到這一點,我添加, -> { where location_type: 'Hospital' }示範:

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 

不幸的是,這會產生在Rails的控制檯錯誤:

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>' 

documentation表明where子句支持一個has_many,也許它不支持自連接。任何人都可以確認嗎?還有另一種方法嗎?

回答

1

請注意,在提供給關聯聲明的任何其他選項之前,需要指定lambda範圍。

請嘗試:

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