【问题标题】:Rails: belongs_to with conditions/scope throwing syntax errorRails:belongs_to 与条件/范围抛出语法错误
【发布时间】:2017-07-25 04:19:35
【问题描述】:

我想选择拥有的公司。我尝试了多种组合,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,但是那个准确的答案也会引发语法错误......

【问题讨论】:

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


    【解决方案1】:

    意外的'\n',期待=>

    你需要切换scopeoptions的顺序

    # 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2016-10-31
      • 2023-03-20
      相关资源
      最近更新 更多