Rails 中的 jQuery Mobile 表单处理
我创建了一个 jQuery Mobile 表单,用于创建“用户”模型。该表单正确回发所有信息,但是我不确定如何处理相应控制器操作中的成功和失败情况。我通常会使用:
# 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
但是这会导致 jQuery Mobile 中出现奇怪的动画(即出现错误时滑出屏幕)。我有什么想法应该如何呈现错误吗?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不了解手机,但如果这基本上是一个ajax请求,那么当出现问题时你需要返回
@user.errors.to_json
。如果这只是一个普通的页面请求,那么您可以在视图中迭代@user.errors
以显示您想要的错误。我也不建议使用 ? :
format.mobile
块内的运算符。在respond_to
内和各个格式块之外执行if
语句,这样您就不必使用 ?当您添加更多格式块时, : 运算符会一遍又一遍地重复。如果你有 3 个格式块,你就会有 3 个 ? : 语句而不仅仅是 1 个 if。如果您只计划使用 1 种格式,则可以在
create
操作中使用respond_with
,然后在控制器顶部。您应该默认执行此操作,因为它可以正常工作并清理您的控制器操作。另外,您不想立即调用
User.create
。您应该使用User.new
,然后在主if
语句中调用@user.save
来确定出现错误时要执行的操作。这删除了 @user.valid?
的调用,我认为更符合惯用语。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 anif
statement within therespond_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 thecreate
action, and then userespond_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 useUser.new
and then call@user.save
on it in your mainif
statement to determine what to do on errors. This removes the call of@user.valid?
and I think is more idiomatically correct.