Rails:belongs_to,条件/范围引发语法错误
我想选择拥有的公司。 我尝试了多种组合, 新的,rails 3,旧学校……所有这些都抛出相同的语法错误unexpected '\n', expecting =>
belongs_to :from, class_name: 'Company', foreign_key: 'from_id', -> { where owned: true } belongs_to :from, class_name: 'Company', foreign_key: 'from_id', -> { where(owned: true) } belongs_to :from, class_name: 'Company', foreign_key: 'from_id', -> { where(:owned => true) } belongs_to :from, class_name: 'Company', foreign_key: 'from_id', condition: { where(:owned => true) }
3年前似乎有人问过这里 ,但似乎没有明确的答案! 还有别的办法吗? Google没有为belongs_to with conditions
或with scope
返回belongs_to with conditions
相关结果
我需要做到这一点 ,但确切的答案是抛出语法错误……
意外’\ n’,期待=>
您需要使用options
切换 scope
的顺序
# File activerecord/lib/active_record/associations.rb, line 1514 def belongs_to(name, scope = nil, options = {}) reflection = Builder::BelongsTo.build(self, name, scope, options) Reflection.add_reflection self, name, reflection end
如您所见, scope
应该是第二个参数 , options
应该是第三个参数 。
这应该工作
belongs_to :from, -> { where owned: true }, class_name: 'Company', foreign_key: 'from_id'