I don''t want user to delete all entries in database. There should be at least one always present. How can I put this validation in model? -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ 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-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
> I don''t want user to delete all entries in database. There should be at > least one always present. How can I put this validation in model?Something like this will stop the last record being deleted. class Model < ActiveRecord::Base before_destroy :ok_to_delete_last_record? private def ok_to_delete_last_record? self.class.count > 1 end end Cheers, Jordan --~--~---------~--~----~------------~-------~--~----~ 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-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
AWDwRoR catches it with this in the applicable model:
def after_destroy
if User.count.zero?
raise "Can''t delete last user"
end
end
It seems like it would already have deleted the record (since it''s
after_destroy), but it will still be there and raise the error before
the data goes away.
-Kyle
On Apr 4, 7:56 am, "Jordan Elver"
<jordan.el...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> > I don''t want user to delete all entries in database. There
should be at
> > least one always present. How can I put this validation in model?
>
> Something like this will stop the last record being deleted.
>
> class Model < ActiveRecord::Base
> before_destroy :ok_to_delete_last_record?
>
> private
>
> def ok_to_delete_last_record?
> self.class.count > 1
> end
>
> end
>
> Cheers,
> Jordan
--~--~---------~--~----~------------~-------~--~----~
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-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---