Topic: validates_uniqueness_of and error handeling

I have to check that a pair of information cannot be added twice, so I wrote this line in my conroller :

validates_uniqueness_of :source_id, :scope => "view_id"

(my view has many sources, but all different)
This seems to work fine, except that if I add an already existing record, I get a big error page that tells me it already exists... the thing is that i do not want this page, i just want that the record is not added and maybe a flash to tell the user about it. How could I handle such error messages ?

Last edited by adamas (2006-11-28 05:59:51)

Re: validates_uniqueness_of and error handeling

You can do this through the controller. Instead of rendering the form again, simply redirect and add a flash if you want:

def create
  @model = Model.find(params[:id)
  if !@model.save
    flash[:notice] = "Unable to save model."
  end
  redirect_to #...
end

Railscasts - Free Ruby on Rails Screencasts

Re: validates_uniqueness_of and error handeling

I have a shopping cart in which people can add whatever they want, then the cart items are added to a document ( that i actually called "view" )

...
@cart.items.each do |source|
  unless @view.sources << source
    flash[:notice]='Not able to add every sources to the view'
  end
end
...

I would like that sources that have already been added to the view are not added again, but the process shouldn't stop, other sources should still be added...

Re: validates_uniqueness_of and error handeling

Finally, I did this :

@cart.items.each do |source|
begin
  @view.sources.find(source.id)
rescue ActiveRecord::RecordNotFound
  @view.sources << source
else
  flash[:notice] = "Not able to add every sources to the view"
end
end

... but it's not a very nice way, I m handeling an error I shouldn't... Does anyone knows a better way to do this ?

Re: validates_uniqueness_of and error handeling

Try:

if @view.sources.include? source
  flash[:notice] = "Not able to add every sources to the view"
else
  @view.sources << source
end

Railscasts - Free Ruby on Rails Screencasts

Re: validates_uniqueness_of and error handeling

Thanks, this is exactly what i needed, it works perfectly.