Rails: belongs_to with conditions/scope throwing syntax error

元气小坏坏 提交于 2019-12-20 03:52:20

问题


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) }

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


回答1:


unexpected '\n', expecting =>

You need to switch the order of scope with 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

As you can see, the scope should be the second parameter and options should be the third parameter.

This should work

belongs_to :from, -> { where owned: true }, class_name: 'Company', foreign_key: 'from_id'


来源:https://stackoverflow.com/questions/45293881/rails-belongs-to-with-conditions-scope-throwing-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!