← Back to Upcase

Best way to specify a default record for a has_many relationship in rails

Hey guys,

how would you address the following issue:

Particularly I’m looking for the options to implement such relationship, i.e. account has multiple addresses and only one is default.

Thanks in advance.

It depends on what you define as ‘default’.

Would the user be specifying their default address? If so, this could be as simple as a boolean ‘default_address’ field on the model. Then its a simple check for that boolean to be true in your logic.

I am sure there are more clever solutions out there, but this would be the simplest for my money.

Yes, exactly. However it also requires to reset “default” flag on all others addresses whenever new one is set as default.

Another idea is to use https://github.com/swanandp/acts_as_list and then treat default address as the top one, then, setting some address as default would be as simple as:

address.move_to_top if params[:set_as_default]

Especially if all you need is to show it the first in some list or combo box :smile:

Or just timestamp set_as_default_at and then special scope, to make the latter win.

Check https://github.com/mechanicles/set_as_primary gem which does the same thing.