Reputation: 961
I am using Rails 4 with postgresql. My model has a title attribute, which is unique. However if the user submits with a duplicate title, I want to increment that by one. Let's say the title is "Crepes", if another user submits with "Crepes", it would save it as "Crepes 1", "Crepes 2" and so on.
The best way I thought was to have another column called display name, and keep the original title in tact. Before create find the ones with the same title and appropriately insert the correct number.
Is there a better way to do this?
Upvotes: 0
Views: 449
Reputation: 1490
The simplest method would indeed be in a before_create method but you don't need a new column (unless you want one) because you can do something like this:
before_create :check_for_uniq
#...
#...
#...
def check_for_uniq
matches = Object.find_by_name(/#{self.name}|#{self.name}_\d/).count
self.name = "#{self.name}_#{matches}"
end
Unless of course you're attempting to have a display title and a hidden title that the end user wouldn't see in which case you most certainly would need another column for the hidden data.
Upvotes: 1
Reputation: 509
I think the best way is to save the number of objects with the same title to the other column, when inserting new one, but saving title, as it was typed:
@my_models_amount = MyModel.where(title: 'Crepes').count
@my_model = MyModel.new(title: 'Crepes', title_counter: @my_models_amount)
and then display it:
def display_title
title_counter.zero? ? title : "#{title} #{title_counter}"
end
Upvotes: 0