我想创建一个包含where
方法过滤器的自联接。
为此,我, -> { 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>'
文档表明一个where
子句支持 a has_many
,也许它不支持自联接。谁能证实这一点?还有另一种方法吗?