Rails:带有条件/范围抛出语法错误的belongs_to [英] Rails: belongs_to with conditions/scope throwing syntax error
问题描述
我想挑选一家拥有的公司.我尝试了多种组合,例如新的,rails 3,旧式的...... ,所有组合都抛出相同的语法错误unexpected '\n', expecting =>
I want to pick companies that are owned. I tried multiple combinations, new, rails 3, old school,... all of which are throwing the same syntax error 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
Someone seems to have asked it 3 years ago here, but there seems to be no definitive answer! Is there any other way? Google's not returning relevant results for belongs_to with conditions
or with scope
我需要完全此,但是该确切答案也将引发语法错误...
I need to do exactly this, but that exact answer's throwing syntax error too...
推荐答案
意外的'\ n',期望=>
unexpected '\n', expecting =>
您需要将的顺序与options
# 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
应该是第三个参数.
As you can see, the scope
should be the second parameter and options
should be the third parameter.
这应该有效
belongs_to :from, -> { where owned: true }, class_name: 'Company', foreign_key: 'from_id'
这篇关于Rails:带有条件/范围抛出语法错误的belongs_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!