【问题标题】:Covering belongs_to condition to Rails 5.1将belongs_to 条件覆盖到Rails 5.1
【发布时间】:2018-02-21 17:24:56
【问题描述】:

我正在将 Rails 3 应用程序升级到 rails 5.1。在 Rails-3 模型中,我有一个类似的条件

has_one :current_contract, :class_name => 'Contract', :conditions => Proc.new { "contract_vw.country = '#{country_id}'" if country_id }

我猜以前的开发者会遵循这个 hack

https://makandracards.com/makandra/983-dynamic-conditions-for-belongs_to-has_many-and-has_one-associations

我不确定如何将其转换为 Rails 5.1

任何帮助表示赞赏。

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

Rails 4+ 的方式是这样编写范围:

has_one :account, -> (country_id) { where('contract_vw.country = ?', country_id) }, class_name: 'Contract'

您已经将if country_id 写入关联,这对我来说似乎很奇怪。尽管where('contract_vw.country = ?', country_id) if country_id 可能有效,但我可能会将其提取到如下方法中:

def country?
  country_id.present?
end

然后,无论您需要什么:

@model.account if @model.country?

【讨论】:

    【解决方案2】:

    如果我正确理解您的用例,您不必一定要使用has_one,在这种情况下我认为不应该使用它,请改用常规方法。

    def current_contract
      contracts.where("contract_vw.country = ?", country_id).first if country_id.present?
      # or ...
      contracts.find_by(country: country_id)
    end
    

    【讨论】:

    • 感谢您提供替代解决方案。在升级 atm 时,我不确定它将如何影响系统。我正在尝试进行最小的更改。
    猜你喜欢
    • 1970-01-01
    • 2011-01-30
    • 2011-01-28
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多