Hi I got a question about error_messages_for helper method in rails. I read that keeping it in the view helps report validation failure. I have used as follows in checkout.rhtml: checkout.rhtml: <div> <%=error_messages_for 'customer'%> <%form_for :customer .....%> ............ <%end%> </div> customer.rb: ......... validates_uniqueness_of :name ......... Now, if I try to give the same name twice, it should display its default message "has already been taken" but mine doesn't just the checkout page is redisplayed. Any suggestions... thanks.
on 2008-10-19 15:36
on 2008-10-19 18:14
Instead of <%= error_messages_for 'customer' %> which is telling error_messages_for to display errors for the string 'customer', which I don't expect to ever work, you should probably use <%= error_messages_for @customer %> assuming that your controller action sets @customer for use by the view. If that's not the case, could you show us the code for your action? Regards, Craig
on 2008-10-20 09:14
Craig D. wrote: > Instead of > > <%= error_messages_for 'customer' %> > > which is telling error_messages_for to display errors for the string > 'customer', which I don't expect to ever work, you should probably use > > <%= error_messages_for @customer %> > > assuming that your controller action sets @customer for use by the view. > If > that's not the case, could you show us the code for your action? > > Regards, > Craig Thank Craig for the reply. I did as you said but ended up getting error "@<Customer not allowed" something like this, so I instead did the other way: def checkout customer = Customer.new end and then: <%=error_messages_for 'customer'%> it worked but I get ugly underline in customer = Customer.new saying that customer hasn't been used. Also I have made .css file for the flash[:notice] but its not getting applied to the generated error message while it does to other error msgs. By the way the above mentioned checkout action is exactly as I've put in the controller and in the view as I've mentioned in my 1st post. Thanks.
on 2008-10-20 16:04
error_messages_for 'customer' by convention looks for @customer. In your controller action, you need to do def checkout @customer = Customer.new end Once you have error_messages_for working, you can view the source of your page to see that error_messages_for generates specific markup for the errors. <div class="errorExplanation" id="errorExplanation"> <h2>1 error prohibited this billing plan from being saved</h2> <p>There were problems with the following fields:</p> <ul> <li>Name can't be blank</li> </ul> </div> (Of course, the text in your error message(s) will be different.) Knowing the markup, you should be able to style it as you like. Regards, Craig