I've got a model which validates_presence_of a field (its a comment
form) and the new comment is added to the top of the comment listing
with a blind_down effect.
However, regardless of whether the field has been entered it still
executes the RJS template. Is there some Ajax-level validation I can
use thats catered for in Rails?
If someone could point me in the direction of a tutorial, method or
anything of help I'd be very grateful.
I've got a model which validates_presence_of a field
However, regardless of whether the field has been
entered it still executes the RJS template.
Of course it does. Barring an error in the app, Rails will _always_
generate a response to a browser request. In the case of non-RJS requests,
Rails validations populate the @error_messages hash which then gets rendered
via a <%= @error_messages_for@object %> directive in your rhtml view. For
RJS requests, the model still populates the @error_messages hash. Problem
is, when you're using RJS you're not going to render that view. The easiest
way to handle your situation is to do the presence check in the controller
and then 'feed' your RJS view, or call a different RJS view, depending on
the result. If you want to send back an error message, use flash.now to
avoid having the message hang around longer than one cycle. Might look
something like...
def my_ajax_response
if params[:thing_to_validate].empty?
flash.now[:notice] => 'that field can't be empty'
else
object_to_save.field_name = params[:thing_to_validate]
object_to_save.save
end
end