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. slides 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_jsonwhen something went wrong. If it’s just a normal page request, then you can iterate over@user.errorsin your view to display the errors however you want.I also wouldn’t recommend using the ? : operator inside of your
format.mobileblock. Do anifstatement within therespond_toand 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_withinside of thecreateaction, and then userespond_to :mobileat 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.createright away. You should rather useUser.newand then call@user.saveon it in your mainifstatement to determine what to do on errors. This removes the call of@user.valid?and I think is more idiomatically correct.