Many thanks, Colin & Frederick--I ended up with this:

  def position_in_category_not_unique
    @items = Item.find( :all, :conditions => [ "category_id = ? AND
position = ?", category_id, position ] )
    single = Item.first( :all, :conditions => [ "category_id = ? AND
position = ?", category_id, position ] )
    if @items.size > 1 || ( single && single.id != id )
      errors.add_to_base "Position #{ position } already exists in #
{ Category.find( category_id ).header }."
    end
  end

Which works, but seems ugly.  Frederick--I'm not sure how to use
validates_uniqueness_of with more than one field--can that be done?

Again, many thanks,
Craig

On Sep 25, 9:35 pm, Frederick Cheung <frederick.che...@gmail.com>
wrote:
> On Sep 26, 12:14 am, Dudebot <craign...@gmail.com> wrote:
>
>
>
>
>
> > I want to write a validate routine to check to enforce that a position
> > must be unique in a category.  (In another category, it doesn't have
> > to and shouldn't need to be unique.)  I write this code which works
> > happily for new items:
>
> > def position_in_category_not_unique
> >   @items = Item.find( :all, :conditions => [ "category_id = ? AND
> > position = ?", category_id, position ] )
> >     if @items.size > 0
> >       errors.add_to_base...
>
> > If, however, I try to *update* an existing item, because it's already
> > in the database, it gives the error.
>
> > Any suggestions on how to approach this?  It's a conceptual question.
> > Do I handle this through the controller somehow?
>
> You could add a condition along the lines of  AND id != self.id. Or
> you could use validates_uniqueness of, which already handles this.
>
> Fred
>
>
>
> > Many, many, many TIA if you tackle this one :)
> > Craig
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to