Rails:belongs_to,条件/范围引发语法错误

时间:2017-07-25 04:19:36

标签: ruby-on-rails ruby-on-rails-5 conditional-associations

我想选择拥有的公司。我尝试了多种组合, new,rails 3,old school,... 所有这些组合都抛出相同的语法错误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年前似乎有人问过here,但似乎没有明确的答案!还有其他方法吗? Google未返回belongs_to with conditionswith scope

的相关结果

我需要完全this,但确切的答案也在抛出语法错误......

1 个答案:

答案 0 :(得分:1)

  

意外' \ n',期待=>

您需要使用scope

切换 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应为第三个​​参数

这应该有效

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