jQuery Mobile Form Handling in Rails
I've created a jQuery Mobile form that is used for creating 'user' models. The form posts back all the information correctly, however I am not sure how to handle the success and failure cases in the action for the corresponding controller. I would typically use:
# POST /user
def create
@user = User.create(params[:user])
respond_to do |format|
format.mobile { @user.valid? ? redirect_to(root_url) : render(action: 'new') }
end
end
However this causes strange animations in the jQuery Mobile (i.e. slid开发者_如何学编程es the screen out on errors). Any ideas how I I should be rendering out the errors?
Thanks!
I don't know about mobile phones, but if this is basically an ajax request, then you need to return @user.errors.to_json
when something went wrong. If it's just a normal page request, then you can iterate over @user.errors
in your view to display the errors however you want.
I also wouldn't recommend using the ? : operator inside of your format.mobile
block. Do an if
statement within the respond_to
and outside of your individual format blocks so that you don't have to use the ? : operator over and over again as you add more format blocks. If you had 3 format blocks, you'd have 3 ? : statements rather than just 1 if.
If you only plan on using 1 type of format, you can use respond_with
inside of the create
action, and then use respond_to :mobile
at the top of the controller. You should do this by default since it just works and it cleans up your controller actions.
Also, you don't want to call User.create
right away. You should rather use User.new
and then call @user.save
on it in your main if
statement to determine what to do on errors. This removes the call of @user.valid?
and I think is more idiomatically correct.
精彩评论