Rails 4.2 脚手架生成的代码,好像是上面一句 respond_to :html,下面各个 respond_with。看起来是简洁了点,但我其实不太理解。 不理解,index, show, new, edit,都没问题,显示正常。 但 redirect_to [:admin, @project], 怎么办? 我用了 respond_with([:admin,@project]) ,会出错,提示说 undefined method `persisted?' for #Array:... 如果生生在下面加一个 redirect_to [:admin, @project],也会出错,提示说有双重 redirect 什么的……
respond_to :html
def index @projects = Project.all respond_with(@projects) end
def show respond_with(@project) end
def new @project = Project.new respond_with(@project) end
def edit end
def create @project = Project.new(project_params) @project.save respond_with(@project) end
def update @project.update(project_params) respond_with(@project) end
def destroy @project.destroy respond_with(@project) end
private def set_project @project = Project.find(params[:id]) end
def project_params params.require(:project).permit(:background, :solution, :result) end end
- 我想跳转到后台的相关页面,这样写会出错,怎么写才正确?
```ruby
def update
@service.update(service_params)
respond_with([:admin,@service])
end
def index @projects = Project.all end
def show end
def new @project = Project.new end
def edit end
def create @project = Project.new(project_params)
respond_to do |format| if @project.save format.html { redirect_to [:admin, @project], notice: '项目创建成功!' } format.json { render :show, status: :created, location: @project } else format.html { render :new } format.json { render json: @project.errors, status: :unprocessable_entity } end end end
def update respond_to do |format| if @project.update(project_params) format.html { redirect_to [:admin, @project], notice: '项目信息成功更新!' } format.json { render :show, status: :ok, location: @project } else format.html { render :edit } format.json { render json: @project.errors, status: :unprocessable_entity } end end end
def destroy @project.destroy respond_to do |format| format.html { redirect_to admin_projects_url, notice: '项目已成功删除!' } format.json { head :no_content } end end
private def set_project @project = Project.find(params[:id]) end
def project_params params.require(:project).permit(:background, :solution, :result) end end
# 解决方案
采用respond_with, 可以参考这个帖子[respond_to Without All the Pain](http://www.justinweiss.com/blog/2014/11/03/respond-to-without-all-the-pain/)了解一下……