Home > Blockchain >  Rails5 how to refactor a find_or_create_by
Rails5 how to refactor a find_or_create_by

Time:11-03

I got some old code I'm trying to port over to Rails 5 (reasons)

And I ran into this....

  def vol_event_for_date(date)
    VolunteerEvent.find_or_create_by_description_and_date("Roster ##{self.id}", date)
  end

  def vol_event_for_weekday(wday)
    VolunteerDefaultEvent.find_or_create_by_description_and_weekday_id("Roster ##{self.id}", wday)
  end

I know from a post I've seen on S.O. that the find_by thingie is an old outdated Rails helper of some kind so my question is...how can I refactor this for a Rails 5.0.7 app?

Thank you for your time.

CodePudding user response:

The change is actually very simple as explained in the Rails 4 Active Record Deprecations

find_or_create_by_... can be rewritten using find_or_create_by(...).

VolunteerEvent.find_or_create_by_description_and_date("Roster ##{self.id}", date)

just changes to

VolunteerEvent.find_or_create_by(description: "Roster ##{self.id}", date: date)
  • Related