0

I am upgrading a Rails 3 app to rails 5.1. In Rails-3 model I have a condition like

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

I guess previous developer follow this hack

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

I am not sure how to convert it to Rails 5.1

Any help appreciated.

learner2017
  • 105
  • 1
  • 3
  • 10
  • do the methods for raisl 4 at https://stackoverflow.com/questions/2462203/rails-has-many-with-dynamic-conditions work? – Brad Werth Feb 21 '18 at 04:24

2 Answers2

1

The Rails 4+ way is to write the scope like so:

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

You've written the if country_id into the association though, which seems real weird to me. Although where('contract_vw.country = ?', country_id) if country_id might work, I'd probably extract that into a method like:

def country?
  country_id.present?
end

And then, wherever you need it:

@model.account if @model.country?
t56k
  • 6,769
  • 9
  • 52
  • 115
0

If I understand your use-case correctly you're not bound to using has_one and in this instance I think it should not be used, use a regular method instead.

def current_contract
  contracts.where("contract_vw.country = ?", country_id).first if country_id.present?
  # or ...
  contracts.find_by(country: country_id)
end
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
  • 1
    Thanks for the alternative solution. As I am upgrading atm, I not sure how it will impact the system. I am trying to make minimal changes. – learner2017 Feb 21 '18 at 12:22