如何调用模型中的重定向方法
我想编写这样的代码
require 'sinatra'
class MyModel
def edit(request)
# ...
updateOK = true
redirect '/article_view' if updateOK
:article_edit
end
end
get '/article_view' do erb :article_view end
get '/article_edit' do erb :article_edit end
post '/article_edit' do
model = MyModel.new
erb model.edit(request)
end
,但它不起作用,它提示: undefined method `redirect' for #
有没有办法在我的自定义中调用重定向方法模型?
哈哈,我知道如何让代码工作,尽管它写错了。
require 'sinatra'
class MyModel
def edit(context)
# ...
updateOK = true
context.redirect '/article_view' if updateOK
:article_edit
end
end
get '/' do erb :index end
get '/article_view' do erb :article_view end
get '/article_edit' do erb :article_edit end
post '/article_edit' do
model = MyModel.new
erb model.edit(self)
end
I wanna to write code like this
require 'sinatra'
class MyModel
def edit(request)
# ...
updateOK = true
redirect '/article_view' if updateOK
:article_edit
end
end
get '/article_view' do erb :article_view end
get '/article_edit' do erb :article_edit end
post '/article_edit' do
model = MyModel.new
erb model.edit(request)
end
but it dosn't work, it tips that: undefined method `redirect' for #<MyModel:0x24e3910>
Is there any way to invoke redirect method in the my custom model?
Haha, I know how to make the code works, despite it write in wrong way.
require 'sinatra'
class MyModel
def edit(context)
# ...
updateOK = true
context.redirect '/article_view' if updateOK
:article_edit
end
end
get '/' do erb :index end
get '/article_view' do erb :article_view end
get '/article_edit' do erb :article_edit end
post '/article_edit' do
model = MyModel.new
erb model.edit(self)
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。该模型不负责路由或重定向。
另外,你的帖子路线看起来很无聊。您向其发送 POST 数据,然后将其传递给模型。模型已创建并保存。您可以将这两者分开,如果 model.save 方法返回 true 则进行重定向。
并不是每个人都喜欢向模型提供参数,所以也要小心这一点。
对于编辑,您通常会使用 PUT 方法,因为您知道模型地址。所以要小心不要混淆它们(除非你知道你在做什么)这会节省你很多思考。
Don't. The model is not responsible for routing or redirecting.
Also, your post route looks borked. You are sending POST data to it which it then passes to the model. The model is created and saved. You can split up these two and if the model.save method returns true you redirect.
Not everybody likes to forfard params to the model, so be careful about that too.
For edits you'd normally use the PUT method because you know the models address. So be careful to not mix them up (unless you know what you're doing) It will save you a lot of thinking.