Hi all
I’ve approached Rails since a couple of months to develop a quick
application for my company. Fantastic framework. As every noob, I do
have some gaps to cover. The one which is giving me a little
frustration, generated by my lack of knowledge is as follows.
I need to make sure the region object is not deleted if there are
countries associated with it. I solved this by putting a
before_destroy methon in the model, as follows:
class Region < ActiveRecord::Base
has_many :countries
validates_presence_of :name
validates_uniqueness_of :name
def before_destroy
unless countries.count == 0
errors.add_to_base “Cannot delete a region with countries
associated”
return false
end
end
end
This prevents the deletion if countries are associated to it. By
adding the error to the errors collection of the region object, I
expected to receive a message on the page by adding the follwing in
the application layout
—cut—
<%= error_messages_for :region %>
<%= yield :layout %>
—cut—
actually the error_messages_for is much longer as it lists all the
objects. The tag works for input forms, but in this specific scenario
no error message is displayed.
The error is however populated, I verified it with the logger.info in
the various steps.
After crushing my head trying to figure out why, I gave up the old
way, finding another solution. But I do not like it because ruby and
rails are very elegant in their syntax. Here is what I did: in the
controller I modified the destroy method like this
def destroy
@region = Region.find(params[:id])
@region.destroy
@region.errors.each_full{|msg| flash[:error] = msg } unless
@region.errors.count == 0
respond_to do |format|
format.html { redirect_to(regions_url) }
format.xml { head :ok }
end
end
I know, it’s an horror, I can name many resons why including the fact
that only the last error is displayed, but could not figure out a
better way. I’m pretty sure that the solution is right in front of me
but cannot find it…
Any suggestion very welcome.
Thanks