Rails Cookbook翻译(六)
处方3.6 使用A ctive Record访问你的数据
问题:
你有已经有一个向控制器提交参数的表单。你想在控制器的一个函数里,创建基于这些参数值的Active Record对象。
解决方案:
例如,你有了下面一个在schema.rb里定义的一个authors表:
db/schema.rb
ActiveRecord::Schema.define(:version => 1) do
create_table “author”, :force => true do |t|
t.column “first_name”, :string
t.column “last_name”, :string
t.column “email” :string
t.column “phone” :string
end
end
在app/models/author.rb里建一个相应的模型:
class Author < ActiveRecord::Base
end
你的创建作者的表单包含以下内容:
<p style="color: green"><%= flash[:notice] %></p>
<h1>Create Author</h1>
<form action="create" method="post">
<p> First Name:
<%= text_field "author", "first_name", "size" => 20 %></p>
<p> Last Name:;
<%= text_field "author", "last_name", "size" => 20 %></p>
<p> Email:;
<%= text_field "author", "email", "size" => 20 %></p>
<p> Phone Number:;
<%= text_field "author", "phone", "size" => 20 %></p>
<input type="submit" value="Save">
</form>
在app/controllers/authors_controller.rb中添加一个create方法创建了一个新的Author对象
def create
@author = Author.new params[:author]
if @author.save
flash[:notice] = 'An author was successfully created.'
redirect_to :action => 'list'
else
flash[:notice] = ‘Failed to create an author.’
Render :action => ‘new’
end
end
讨论:
在Authors控制器中,我们通过调用Active Record的构造函数创建了一个Author实例。这个构造函数被传递了一个与author表相关的属性值组成的hash表,在这个例子中我们将author hash表作为实参传递给形参为params hash的表。这个author hash表包含了我们在创建author表所填的所有的值。
当我们试图保存这些数据的时候,他会执行真正的SQL插入操作。如果没有什么错误的话,我们创建了一个flash信息会指示成功,并且重定向到list动作。如果或许由于没有通过验证,对象没有被保存,我们就会重新呈现那个表单。
你还可以参考:
3.8节