Ruby on rails 创建允许我更新对象的“显示”页面的正确方法

Ruby on rails 创建允许我更新对象的“显示”页面的正确方法,ruby-on-rails,Ruby On Rails,我有以下控制器 class ProductController < ApplicationController def show id = params[:id] @product = Product.find(id) end def update render text:params end end 当我点击update时,它将呈现请求 {utf8=>✓, _方法=>patch,authenticity_token=>sRzyQ0nP2ycW

我有以下控制器

class ProductController < ApplicationController

  def show
    id = params[:id]
    @product = Product.find(id)
  end

  def update
    render text:params
  end
end
当我点击update时,它将呈现请求

{utf8=>✓, _方法=>patch,authenticity_token=>sRzyQ0nP2ycWwgaS9eu5vHcID1b+hIl5Vho3KfX3XuE=,产品=>{name=>testname,quantity=>2},提交=>Update,action=>Update,controller=>product,id=>1}

我将修改更新方法以保存新属性,并将用户重定向回显示页面


我应该这样更新数据库对象吗?

如果我理解您的问题,您必须:

  def update
    @product = Product.find(params[:id])

    if @product.update_attributes(params[:product])
      redirect_to @product, notice: 'Product was successfully updated.'
    else
      render action: 'show'
    end
  end
希望这有帮助

编辑

Rails方式不是显示动作,而是使用编辑动作来呈现表单。看看scaffold:railsgscaffoldfoo,了解rails是如何工作的


但似乎你想要的是一个就地编辑。观看Railscasts。

是的,这是rails应用程序中非常典型的场景。
  def update
    @product = Product.find(params[:id])

    if @product.update_attributes(params[:product])
      redirect_to @product, notice: 'Product was successfully updated.'
    else
      render action: 'show'
    end
  end