Rails 新人 第一天 Rails

匿名 · 2013年05月23日 · 最后由 owlran 回复于 2013年05月24日 · 2243 次阅读

看了 Agile Web Develoment with Rails 后,跟着写 Depot 的代码,用 scaffold 生产脚手架。y 有些地方的代码,很不理解,为什么 create 成功后就到了 show.html.erb 呢。

def create
    @product = Product.new(params[:product])

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render json: @product, status: :created, location: @product }
      else
        format.html { render action: "new" }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

redirect_to @product,为什么就到了 show.html.erb 呢

rails 默认是使用 RESTful 方式,rails 很多地方都是使用默认配置,默认的配置节省了很多时间

简单来说,redirect_to @product 表示重定向到 Products 这个 resource 的某个实例,在 URL 中缺省表现为 http://domain.tld/products/1 的形式 (最后的数字是这个 product 的 id,是个数字,不一定是 1 )。然后对单个实例的 GET 动作是对应 controller 中的 show 方法,而 show 方法则缺省渲染 view 里面的 show.html.erb .

以上皆是 rails 的 convention . 约定优于配置...

匿名 #3 2013年05月24日

现在了然了,解释的很清楚,继续 Rails 入门

好早啊大家

匿名 #5 2013年05月24日

早上好啊

需要 登录 后方可回复, 如果你还没有账号请 注册新账号