我想创建一个包含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>'
documentation表示where
子句支持has_many
,可能不支持自联接。谁能证实这一点?还有另一种方法吗?
答案 0 :(得分:1)
请注意,在提供给关联声明的任何其他选项之前,需要指定lambda范围。
请尝试:
has_many :hospitals, -> { where location_type: 'Hospital' }, class_name: "Location", foreign_key: "parent_id"