将redirect_to与特定的ActiveRecord对象一起使用以创建指向该对象的链接

mai*_*aik 6 ruby-on-rails

我将在http://ruby.railstutorial.org/上阅读Michael Hartl的教程.它基本上是一个留言板应用程序,用户可以发布消息,其他人可以留下回复.现在我正在创造Users.里面的UsersController东西看起来像这样:

    class UsersController < ApplicationController
      def new
        @user = User.new
      end

      def show
        @user = User.find(params[:id])
      end

      def create
        @user = User.new(params[:user])
        if @user.save
          flash[:success] = "Welcome to the Sample App!"
          redirect_to @user
        else
          render 'new'
        end    
      end
    end
Run Code Online (Sandbox Code Playgroud)

作者说以下几行是等价的.这对我有意义:

    @user = User.new(params[:user])
    is equivalent to
    @user = User.new(name: "Foo Bar", email: "foo@invalid",
             password: "foo", password_confirmation: "bar")
Run Code Online (Sandbox Code Playgroud)

redirect_to @user重定向到show.html.erb.这究竟是如何工作的?怎么知道去show.html.erb

Kev*_*ell 13

这一切都是通过Rail的宁静路由的魔力来处理的.具体来说,有一个约定,即执行redirect_to特定对象会转到该对象的show页面.Rails知道这@user是一个活动的记录对象,所以它解释为知道你想要转到对象的显示页面.

以下是Rails指南相应部分的一些细节- 来自Outside In的Rails路由.:

# If you wanted to link to just a magazine, you could leave out the
# Array:

<%= link_to "Magazine details", @magazine %>

# This allows you to treat instances of your models as URLs, and is a
# key advantage to using the resourceful style.
Run Code Online (Sandbox Code Playgroud)

基本上,在routes.rb文件中使用restful resources会为您提供直接从ActiveRecord对象创建url的"快捷方式".