【问题标题】:after upgrading to rails 5.1.7 have an error ArgumentError: invalid argument: nil升级到 rails 5.1.7 后出现错误 ArgumentError: invalid argument: nil
【发布时间】:2020-08-25 21:39:49
【问题描述】:

升级到 rails 5.1.7 后出现错误 ArgumentError: invalid argument: nil.

测试:

describe 'default_for scope' do
    it 'joins intel_tags' do
      scope = IntelTagging.default_for('something')
      expect(scope.joins_values).to include(:intel_tag)
    end

    it 'uses IntelTag.default_for' do
      expect(IntelTag).to receive(:default_for).with('something')
      IntelTagging.default_for('something')
    end
  end

型号:

class IntelTagging < ApplicationRecord
...
belongs_to :intel_tag, inverse_of: :intel_taggings, optional: true
accepts_nested_attributes_for :intel_tag

validates_presence_of :intel_tag

scope :default_for, ->(type) {
    joins(:intel_tag).merge(IntelTag.default_for(type))
  }

  scope :key, ->(key) { joins(:intel_tag).merge(IntelTag.key(key)) }
...
end
class IntelTag < ApplicationRecord
...
has_many :intel_taggings, inverse_of: :intel_tag, dependent: :destroy

scope :default_for, ->(string) { where(arel_table[:default_for].matches("%#{string}%")) }
...
end

我发现在 rails 5 中它发生了一些变化 -> 当将 nilfalse 传递给 Relation#merge 时,提升 ArgumentError。 这些不是在关系中合并的有效值,因此它应该尽早警告用户。

我做了以下很丑陋的事情:

scope :default_for, ->(type) {
    joins_intel_tag = joins(:intel_tag)
    joins_intel_tag.merge(IntelTag.default_for(type)) if joins_intel_tag.present?
  }

但还是有错误

 (IntelTag(id: integer, managed: boolean, default_for: text, unmanaged_name: string, name_en: string, name_fr: string, name_it: string, name_de: string, deleted_at: datetime, created_at: datetime, updated_at: datetime, key: string) (class)).default_for("something")
           expected: 1 time with arguments: ("something")
           received: 0 times

【问题讨论】:

    标签: ruby-on-rails activerecord rspec scope


    【解决方案1】:

    目前为使测试通过,但仍在调查和寻找更好的解决方案:

    scope :default_for, ->(type) {
        joins(:intel_tag).merge(IntelTag.default_for(type)) unless IntelTag.default_for(type).nil?
      }
    
      scope :key, ->(key) {
        IntelTag.key(key).nil? ? joins(:intel_tag) : joins(:intel_tag).merge(IntelTag.key(key))
      }
    

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2020-01-19
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多