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
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.