我将在
http://ruby.railstutorial.org/阅读Michael Hartl的教程.它基本上是一个留言板应用程序,用户可以发布消息,其他人可以留下回复.现在我正在创建用户.在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
作者说以下几行是等价的.这对我有意义:
@user = User.new(params[:user]) is equivalent to @user = User.new(name: "Foo Bar",email: "foo@invalid",password: "foo",password_confirmation: "bar")
redirect_to @user重定向到show.html.erb.这究竟是如何工作的?怎么知道去show.html.erb?
解决方法
这一切都是通过Rail的宁静路由的魔力来处理的.具体来说,有一个约定,即对特定对象执行redirect_转到该对象的显示页面. Rails知道@user是一个活动的记录对象,因此它将其解释为知道你想要转到该对象的显示页面.
以下是Rails Guide – Rails Routing from the Outside In.相应部分的一些细节:
# 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.
基本上,在routes.rb文件中使用restful资源为您提供了直接从ActiveRecord对象创建url的“快捷方式”.