问题
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