(Rails) 如何让 'id' 退出编辑 url
(Rails) How to get 'id' out of edit url
我有一个模型叫做 studies
。
操作重定向后 redirect_to edit_study_path(@new_study)
,
URL: http://localhost:3000/studies/2/edit
.
在通过 id
之后是否可以自定义一个 url?
例如,http://localhost:3000/study
(仍然进入编辑路径,并且仍然在参数中使用 :id
)
我猜你想要编辑当前的研究?
在这种情况下,可以在路由中使用 ressource
而不是 ressources
。
举个例子:
#in routes.rb
resources :studies
resource :study
默认情况下,它们都将 link 到 StudiesController 并调用相同的操作(例如,在您的情况下进行编辑),但在两个不同的路由中
get "/studies/:id/edit" => "studies#edit"
get "/study/edit" => "studies#edit"
在您的编辑操作中,您应该设置以正确处理参数:
def edit
@study = params[:id].nil? ? current_study : Study.find(params[:id])
end
请注意,您在某处需要一个 current_study 方法,并将 current_study 存储在 cookies/sessions 中以使其工作。
示例:
# In application_controller.rb
def current_study
@current_study ||= Study.find_by(id: session[:current_study_id]) #using find_by doesn't raise exception if doesn't exists
end
def current_study= x
@current_study = x
session[:current_study_id] = x.id
end
#... And back to study controller
def create
#...
#Eg. setup current_study and go to edit after creation
if study.save
self.current_study = study
redirect_to study_edit_path #easy peesy
end
end
编码愉快,
亚辛。
我有一个模型叫做 studies
。
操作重定向后 redirect_to edit_study_path(@new_study)
,
URL: http://localhost:3000/studies/2/edit
.
在通过 id
之后是否可以自定义一个 url?
例如,http://localhost:3000/study
(仍然进入编辑路径,并且仍然在参数中使用 :id
)
我猜你想要编辑当前的研究?
在这种情况下,可以在路由中使用 ressource
而不是 ressources
。
举个例子:
#in routes.rb
resources :studies
resource :study
默认情况下,它们都将 link 到 StudiesController 并调用相同的操作(例如,在您的情况下进行编辑),但在两个不同的路由中
get "/studies/:id/edit" => "studies#edit"
get "/study/edit" => "studies#edit"
在您的编辑操作中,您应该设置以正确处理参数:
def edit
@study = params[:id].nil? ? current_study : Study.find(params[:id])
end
请注意,您在某处需要一个 current_study 方法,并将 current_study 存储在 cookies/sessions 中以使其工作。
示例:
# In application_controller.rb
def current_study
@current_study ||= Study.find_by(id: session[:current_study_id]) #using find_by doesn't raise exception if doesn't exists
end
def current_study= x
@current_study = x
session[:current_study_id] = x.id
end
#... And back to study controller
def create
#...
#Eg. setup current_study and go to edit after creation
if study.save
self.current_study = study
redirect_to study_edit_path #easy peesy
end
end
编码愉快,
亚辛。