0

Assume I have 2 models: Device and Setting. I need to track and control the settings for each device. The number of devices and settings will grow over time. Clearly a many to many situation so I was going to use the "has_many :through" approach with a 3rd column for the setting value in the device_settings table.

My challenge is that as new settings are added I want to ensure that all devices have all settings populated in the device_settings table (the Settings model has a default_value attribute that can be used to populte the device_settings.value attribute). Once a setting is added to the table its easy to ensure that new devices or edited devices insert the new setting row. But is there a clean way to retro fit existing devices?

At some point the system will update the device settings and I want to avoid complex logic to handle missing values during this process. I think its better to enforce that the bridge table has all the rows in the first place.

I can, and have, written some ugly code (loops etc) to populate the device_settings table on the :after_save on the Setting model but I am looking for something cleaner.

Thank you

Matthew Doering
  • 321
  • 3
  • 9

1 Answers1

0

Would this fit the bill?

SettingsController

  def create
   ...
    if @setting.save
      Device.all.each {|d| d.settings << @setting}
    end
  end
end
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • This will work as long as you've set up the default value for that 3rd column you mentioned as discussed in http://stackoverflow.com/questions/1550688/how-do-i-create-a-default-value-for-attributes-in-rails-activerecords-model – Peter Alfvin Jul 08 '13 at 22:11
  • Yes this is close to what I have, though yours is written cleaner. I also created a companion to handle delete and updates etc. It just starts looking very redundant. Any chance that someone has gem that might clean this up? This seems to be a resonably common use case. If not this answer looks to be the best. – Matthew Doering Jul 09 '13 at 01:08