I'm looking to make my db:seed
task a little more dynamic by allowing certain entries in my application to be created or updated (or nothing at all) based on the values of in db/seeds.rb
and the current state of the backend database. I'm also looking to simplify the functions that carry this logic out.
I'd like to avoid this:
def create_or_update_config(key, value)
...
if config_entry.value != value
config_entry.value
end
if config_entry.changed?
config_entry.save
end
...
end
And instead have something simplistic:
def create_or_update_config(key, value)
...
config_entry.value = value
if config_entry.changed?
config_entry.save
end
...
end
Is ActiveRecord smart enough to know if attribute values have changed even if they've been set (with the same value)?
Yes. ActiveRecord's changed?
method will return true only if there were mutations since the last save. From an example using my own app's console (Rails 5.1.6):
irb(main):013:0> config.value
=> "http://localhost:3100"
irb(main):014:0> config.value = "http://localhost:3100"
=> "http://localhost:3100"
irb(main):015:0> config.changed?
=> false
irb(main):016:0> config.value = "anything else"
=> "anything else"
irb(main):017:0> config.changed?
=> true