rails 2.3.8 → 2.3.9.pre
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- data/CHANGELOG +3 -2
- data/Rakefile +6 -7
- data/builtin/rails_info/rails/info.rb +1 -1
- data/environments/boot.rb +6 -2
- data/environments/environment.rb +1 -1
- data/lib/initializer.rb +44 -20
- data/lib/rails/plugin.rb +1 -1
- data/lib/rails/plugin/loader.rb +3 -3
- data/lib/rails/version.rb +1 -1
- data/lib/rails_generator/generators/components/migration/migration_generator.rb +1 -1
- data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +2 -1
- metadata +25 -124
- data/guides/files/javascripts/code_highlighter.js +0 -188
- data/guides/files/javascripts/guides.js +0 -8
- data/guides/files/javascripts/highlighters.js +0 -90
- data/guides/files/stylesheets/main.css +0 -441
- data/guides/files/stylesheets/print.css +0 -52
- data/guides/files/stylesheets/reset.css +0 -43
- data/guides/files/stylesheets/style.css +0 -13
- data/guides/files/stylesheets/syntax.css +0 -31
- data/guides/images/belongs_to.png +0 -0
- data/guides/images/book_icon.gif +0 -0
- data/guides/images/bullet.gif +0 -0
- data/guides/images/chapters_icon.gif +0 -0
- data/guides/images/check_bullet.gif +0 -0
- data/guides/images/credits_pic_blank.gif +0 -0
- data/guides/images/csrf.png +0 -0
- data/guides/images/customized_error_messages.png +0 -0
- data/guides/images/error_messages.png +0 -0
- data/guides/images/feature_tile.gif +0 -0
- data/guides/images/footer_tile.gif +0 -0
- data/guides/images/fxn.jpg +0 -0
- data/guides/images/grey_bullet.gif +0 -0
- data/guides/images/habtm.png +0 -0
- data/guides/images/has_many.png +0 -0
- data/guides/images/has_many_through.png +0 -0
- data/guides/images/has_one.png +0 -0
- data/guides/images/has_one_through.png +0 -0
- data/guides/images/header_backdrop.png +0 -0
- data/guides/images/header_tile.gif +0 -0
- data/guides/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/images/i18n/demo_translated_en.png +0 -0
- data/guides/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/images/i18n/demo_translation_missing.png +0 -0
- data/guides/images/i18n/demo_untranslated.png +0 -0
- data/guides/images/icons/README +0 -5
- data/guides/images/icons/callouts/1.png +0 -0
- data/guides/images/icons/callouts/10.png +0 -0
- data/guides/images/icons/callouts/11.png +0 -0
- data/guides/images/icons/callouts/12.png +0 -0
- data/guides/images/icons/callouts/13.png +0 -0
- data/guides/images/icons/callouts/14.png +0 -0
- data/guides/images/icons/callouts/15.png +0 -0
- data/guides/images/icons/callouts/2.png +0 -0
- data/guides/images/icons/callouts/3.png +0 -0
- data/guides/images/icons/callouts/4.png +0 -0
- data/guides/images/icons/callouts/5.png +0 -0
- data/guides/images/icons/callouts/6.png +0 -0
- data/guides/images/icons/callouts/7.png +0 -0
- data/guides/images/icons/callouts/8.png +0 -0
- data/guides/images/icons/callouts/9.png +0 -0
- data/guides/images/icons/caution.png +0 -0
- data/guides/images/icons/example.png +0 -0
- data/guides/images/icons/home.png +0 -0
- data/guides/images/icons/important.png +0 -0
- data/guides/images/icons/next.png +0 -0
- data/guides/images/icons/note.png +0 -0
- data/guides/images/icons/prev.png +0 -0
- data/guides/images/icons/tip.png +0 -0
- data/guides/images/icons/up.png +0 -0
- data/guides/images/icons/warning.png +0 -0
- data/guides/images/nav_arrow.gif +0 -0
- data/guides/images/polymorphic.png +0 -0
- data/guides/images/posts_index.png +0 -0
- data/guides/images/rails_guides_logo.gif +0 -0
- data/guides/images/rails_logo_remix.gif +0 -0
- data/guides/images/rails_welcome.png +0 -0
- data/guides/images/session_fixation.png +0 -0
- data/guides/images/tab_grey.gif +0 -0
- data/guides/images/tab_info.gif +0 -0
- data/guides/images/tab_note.gif +0 -0
- data/guides/images/tab_red.gif +0 -0
- data/guides/images/tab_yellow.gif +0 -0
- data/guides/images/tab_yellow.png +0 -0
- data/guides/images/validation_error_messages.png +0 -0
- data/guides/rails_guides.rb +0 -42
- data/guides/rails_guides/generator.rb +0 -138
- data/guides/rails_guides/helpers.rb +0 -34
- data/guides/rails_guides/indexer.rb +0 -55
- data/guides/rails_guides/textile_extensions.rb +0 -41
- data/guides/source/2_2_release_notes.textile +0 -422
- data/guides/source/2_3_release_notes.textile +0 -610
- data/guides/source/action_controller_overview.textile +0 -776
- data/guides/source/action_mailer_basics.textile +0 -424
- data/guides/source/active_record_basics.textile +0 -135
- data/guides/source/active_record_querying.textile +0 -969
- data/guides/source/activerecord_validations_callbacks.textile +0 -1086
- data/guides/source/association_basics.textile +0 -1781
- data/guides/source/caching_with_rails.textile +0 -524
- data/guides/source/command_line.textile +0 -589
- data/guides/source/configuring.textile +0 -234
- data/guides/source/contribute.textile +0 -71
- data/guides/source/contributing_to_rails.textile +0 -239
- data/guides/source/credits.erb.textile +0 -52
- data/guides/source/debugging_rails_applications.textile +0 -709
- data/guides/source/form_helpers.textile +0 -766
- data/guides/source/getting_started.textile +0 -1297
- data/guides/source/i18n.textile +0 -912
- data/guides/source/index.erb.textile +0 -124
- data/guides/source/layout.html.erb +0 -103
- data/guides/source/layouts_and_rendering.textile +0 -979
- data/guides/source/migrations.textile +0 -591
- data/guides/source/nested_model_forms.textile +0 -222
- data/guides/source/performance_testing.textile +0 -531
- data/guides/source/plugins.textile +0 -1512
- data/guides/source/rails_on_rack.textile +0 -309
- data/guides/source/routing.textile +0 -903
- data/guides/source/security.textile +0 -986
- data/guides/source/testing.textile +0 -951
@@ -1,424 +0,0 @@
|
|
1
|
-
h2. Action Mailer Basics
|
2
|
-
|
3
|
-
This guide should provide you with all you need to get started in sending and receiving emails from/to your application, and many internals of Action Mailer. It also covers how to test your mailers.
|
4
|
-
|
5
|
-
endprologue.
|
6
|
-
|
7
|
-
h3. Introduction
|
8
|
-
|
9
|
-
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating models that inherit from +ActionMailer::Base+ that live alongside other models in +app/models+. Those models have associated views that appear alongside controller views in +app/views+.
|
10
|
-
|
11
|
-
h3. Sending Emails
|
12
|
-
|
13
|
-
This section will provide a step-by-step guide to creating a mailer and its views.
|
14
|
-
|
15
|
-
h4. Walkthrough to Generating a Mailer
|
16
|
-
|
17
|
-
h5. Create the Mailer
|
18
|
-
|
19
|
-
<shell>
|
20
|
-
./script/generate mailer UserMailer
|
21
|
-
exists app/models/
|
22
|
-
create app/views/user_mailer
|
23
|
-
exists test/unit/
|
24
|
-
create test/fixtures/user_mailer
|
25
|
-
create app/models/user_mailer.rb
|
26
|
-
create test/unit/user_mailer_test.rb
|
27
|
-
</shell>
|
28
|
-
|
29
|
-
So we got the model, the fixtures, and the tests.
|
30
|
-
|
31
|
-
h5. Edit the Model
|
32
|
-
|
33
|
-
+app/models/user_mailer.rb+ contains an empty mailer:
|
34
|
-
|
35
|
-
<ruby>
|
36
|
-
class UserMailer < ActionMailer::Base
|
37
|
-
end
|
38
|
-
</ruby>
|
39
|
-
|
40
|
-
Let's add a method called +welcome_email+, that will send an email to the user's registered email address:
|
41
|
-
|
42
|
-
<ruby>
|
43
|
-
class UserMailer < ActionMailer::Base
|
44
|
-
def welcome_email(user)
|
45
|
-
recipients user.email
|
46
|
-
from "My Awesome Site Notifications <notifications@example.com>"
|
47
|
-
subject "Welcome to My Awesome Site"
|
48
|
-
sent_on Time.now
|
49
|
-
body {:user => user, :url => "http://example.com/login"}
|
50
|
-
end
|
51
|
-
end
|
52
|
-
</ruby>
|
53
|
-
|
54
|
-
Here is a quick explanation of the options presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of ActionMailer user-settable attributes section.
|
55
|
-
|
56
|
-
|recipients| The recipients of the email. It can be a string or, if there are multiple recipients, an array of strings|
|
57
|
-
|from| The from address of the email|
|
58
|
-
|subject| The subject of the email|
|
59
|
-
|sent_on| The timestamp for the email|
|
60
|
-
|
61
|
-
The keys of the hash passed to +body+ become instance variables in the view. Thus, in our example the mailer view will have a +@user+ and a +@url+ instance variables available.
|
62
|
-
|
63
|
-
h5. Create a Mailer View
|
64
|
-
|
65
|
-
Create a file called +welcome_email.text.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML:
|
66
|
-
|
67
|
-
<erb>
|
68
|
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
69
|
-
<html>
|
70
|
-
<head>
|
71
|
-
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
|
72
|
-
</head>
|
73
|
-
<body>
|
74
|
-
<h1>Welcome to example.com, <%=h @user.first_name %></h1>
|
75
|
-
<p>
|
76
|
-
You have successfully signed up to example.com, and your username is: <%= @user.login %>.<br/>
|
77
|
-
To login to the site, just follow this link: <%=h @url %>.
|
78
|
-
</p>
|
79
|
-
<p>Thanks for joining and have a great day!</p>
|
80
|
-
</body>
|
81
|
-
</html>
|
82
|
-
</erb>
|
83
|
-
|
84
|
-
Had we wanted to send text-only emails, the file would have been called +welcome_email.text.plain.erb+. Rails sets the content type of the email to be the one in the filename.
|
85
|
-
|
86
|
-
h5. Wire It Up So That the System Sends the Email When a User Signs Up
|
87
|
-
|
88
|
-
There are three ways to achieve this. One is to send the email from the controller that sends the email, another is to put it in a +before_create+ callback in the user model, and the last one is to use an observer on the user model. Whether you use the second or third methods is up to you, but staying away from the first is recommended. Not because it's wrong, but because it keeps your controller clean, and keeps all logic related to the user model within the user model. This way, whichever way a user is created (from a web form, or from an API call, for example), we are guaranteed that the email will be sent.
|
89
|
-
|
90
|
-
Let's see how we would go about wiring it up using an observer:
|
91
|
-
|
92
|
-
In +config/environment.rb+:
|
93
|
-
|
94
|
-
<ruby>
|
95
|
-
Rails::Initializer.run do |config|
|
96
|
-
# ...
|
97
|
-
config.active_record.observers = :user_observer
|
98
|
-
end
|
99
|
-
</ruby>
|
100
|
-
|
101
|
-
You can place the observer in +app/models+ where it will be loaded automatically by Rails.
|
102
|
-
|
103
|
-
Now create a file called +user_observer.rb+ in +app/models+ depending on where you stored it, and make it look like:
|
104
|
-
|
105
|
-
<ruby>
|
106
|
-
class UserObserver < ActiveRecord::Observer
|
107
|
-
def after_create(user)
|
108
|
-
UserMailer.deliver_welcome_email(user)
|
109
|
-
end
|
110
|
-
end
|
111
|
-
</ruby>
|
112
|
-
|
113
|
-
Notice how we call +deliver_welcome_email+? In Action Mailer we send emails by calling +deliver_<method_name>+. In UserMailer, we defined a method called +welcome_email+, and so we deliver the email by calling +deliver_welcome_email+. The next section will go through how Action Mailer achieves this.
|
114
|
-
|
115
|
-
h4. Action Mailer and Dynamic +deliver_<method_name>+ methods
|
116
|
-
|
117
|
-
So how does Action Mailer understand this +deliver_welcome_email+ call? If you read the documentation (http://api.rubyonrails.org/files/vendor/rails/actionmailer/README.html), you will find this in the "Sending Emails" section:
|
118
|
-
|
119
|
-
You never instantiate your mailer class. Rather, your delivery instance methods are automatically wrapped in class methods that start with the word +deliver_+ followed by the name of the mailer method that you would like to deliver.
|
120
|
-
|
121
|
-
So, how exactly does this work?
|
122
|
-
|
123
|
-
Looking at the +ActionMailer::Base+ source, you will find this:
|
124
|
-
|
125
|
-
<ruby>
|
126
|
-
def method_missing(method_symbol, *parameters)#:nodoc:
|
127
|
-
case method_symbol.id2name
|
128
|
-
when /^create_([_a-z]\w*)/ then new($1, *parameters).mail
|
129
|
-
when /^deliver_([_a-z]\w*)/ then new($1, *parameters).deliver!
|
130
|
-
when "new" then nil
|
131
|
-
else super
|
132
|
-
end
|
133
|
-
end
|
134
|
-
</ruby>
|
135
|
-
|
136
|
-
Hence, if the method name starts with +deliver_+ followed by any combination of lowercase letters or underscore, +method_missing+ calls +new+ on your mailer class (+UserMailer+ in our example above), sending the combination of lower case letters or underscore, along with the parameters. The resulting object is then sent the +deliver!+ method, which well... delivers it.
|
137
|
-
|
138
|
-
h4. Complete List of Action Mailer User-Settable Attributes
|
139
|
-
|
140
|
-
|bcc| The BCC addresses of the email|
|
141
|
-
|body| The body of the email. This is either a hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual body of the message|
|
142
|
-
|cc| The CC addresses for the email|
|
143
|
-
|charset| The charset to use for the email. This defaults to the +default_charset+ specified for ActionMailer::Base.|
|
144
|
-
|content_type| The content type for the email. This defaults to "text/plain" but the filename may specify it|
|
145
|
-
|from| The from address of the email|
|
146
|
-
|reply_to| The address (if different than the "from" address) to direct replies to this email|
|
147
|
-
|headers| Additional headers to be added to the email|
|
148
|
-
|implicit_parts_order| The order in which parts should be sorted, based on the content type. This defaults to the value of +default_implicit_parts_order+|
|
149
|
-
|mime_version| Defaults to "1.0", but may be explicitly given if needed|
|
150
|
-
|recipient| The recipient addresses of the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|
151
|
-
|sent_on| The timestamp on which the message was sent. If unset, the header will be set by the delivery agent|
|
152
|
-
|subject| The subject of the email|
|
153
|
-
|template| The template to use. This is the "base" template name, without the extension or directory, and may be used to have multiple mailer methods share the same template|
|
154
|
-
|
155
|
-
h4. Mailer Views
|
156
|
-
|
157
|
-
Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.text.html.erb+ for the HTML version and +welcome_email.text.plain.erb+ for the plain text version.
|
158
|
-
|
159
|
-
To change the default mailer view for your action you do something like:
|
160
|
-
|
161
|
-
<ruby>
|
162
|
-
class UserMailer < ActionMailer::Base
|
163
|
-
def welcome_email(user)
|
164
|
-
recipients user.email
|
165
|
-
from "My Awesome Site Notifications<notifications@example.com>"
|
166
|
-
subject "Welcome to My Awesome Site"
|
167
|
-
sent_on Time.now
|
168
|
-
body {:user => user, :url => "http://example.com/login"}
|
169
|
-
content_type "text/html"
|
170
|
-
# use some_other_template.text.(html|plain).erb instead
|
171
|
-
template "some_other_template"
|
172
|
-
end
|
173
|
-
</ruby>
|
174
|
-
|
175
|
-
h4. Action Mailer Layouts
|
176
|
-
|
177
|
-
Just like controller views, you can also have mailer layouts. The layout name needs to end in "_mailer" to be automatically recognized by your mailer as a layout. So in our UserMailer example, we need to call our layout +user_mailer.text.(html|plain).erb+. In order to use a different file just use:
|
178
|
-
|
179
|
-
<ruby>
|
180
|
-
class UserMailer < ActionMailer::Base
|
181
|
-
layout 'awesome' # use awesome.text.(html|plain).erb as the layout
|
182
|
-
end
|
183
|
-
</ruby>
|
184
|
-
|
185
|
-
Just like with controller views, use +yield+ to render the view inside the layout.
|
186
|
-
|
187
|
-
h4. Generating URLs in Action Mailer Views
|
188
|
-
|
189
|
-
URLs can be generated in mailer views using +url_for+ or named routes.
|
190
|
-
Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the +:host+, +:controller+, and +:action+:
|
191
|
-
|
192
|
-
<erb>
|
193
|
-
<%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
|
194
|
-
</erb>
|
195
|
-
|
196
|
-
When using named routes you only need to supply the +:host+:
|
197
|
-
|
198
|
-
<erb>
|
199
|
-
<%= users_url(:host => "example.com") %>
|
200
|
-
</erb>
|
201
|
-
|
202
|
-
Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the "_url" variant makes sense.
|
203
|
-
|
204
|
-
It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in
|
205
|
-
the +ActionMailer::Base.default_url_options+ hash as follows:
|
206
|
-
|
207
|
-
<erb>
|
208
|
-
ActionMailer::Base.default_url_options[:host] = "example.com"
|
209
|
-
</erb>
|
210
|
-
|
211
|
-
This can also be set as a configuration option in +config/environment.rb+:
|
212
|
-
|
213
|
-
<erb>
|
214
|
-
config.action_mailer.default_url_options = { :host => "example.com" }
|
215
|
-
</erb>
|
216
|
-
|
217
|
-
If you set a default +:host+ for your mailers you need to pass +:only_path => false+ to +url_for+. Otherwise it doesn't get included.
|
218
|
-
|
219
|
-
h4. Sending Multipart Emails
|
220
|
-
|
221
|
-
Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.plain.erb+ and +welcome_email.text.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
|
222
|
-
|
223
|
-
To explicitly specify multipart messages, you can do something like:
|
224
|
-
|
225
|
-
<ruby>
|
226
|
-
class UserMailer < ActionMailer::Base
|
227
|
-
def welcome_email(user)
|
228
|
-
recipients user.email_address
|
229
|
-
subject "New account information"
|
230
|
-
from "system@example.com"
|
231
|
-
content_type "multipart/alternative"
|
232
|
-
|
233
|
-
part :content_type => "text/html",
|
234
|
-
:body => "<p>html content, can also be the name of an action that you call<p>"
|
235
|
-
|
236
|
-
part "text/plain" do |p|
|
237
|
-
p.body = "text content, can also be the name of an action that you call"
|
238
|
-
end
|
239
|
-
end
|
240
|
-
end
|
241
|
-
</ruby>
|
242
|
-
|
243
|
-
h4. Sending Emails with Attachments
|
244
|
-
|
245
|
-
Attachments can be added by using the +attachment+ method:
|
246
|
-
|
247
|
-
<ruby>
|
248
|
-
class UserMailer < ActionMailer::Base
|
249
|
-
def welcome_email(user)
|
250
|
-
recipients user.email_address
|
251
|
-
subject "New account information"
|
252
|
-
from "system@example.com"
|
253
|
-
content_type "multipart/alternative"
|
254
|
-
|
255
|
-
attachment :content_type => "image/jpeg",
|
256
|
-
:body => File.read("an-image.jpg")
|
257
|
-
|
258
|
-
attachment "application/pdf" do |a|
|
259
|
-
a.body = generate_your_pdf_here()
|
260
|
-
end
|
261
|
-
end
|
262
|
-
end
|
263
|
-
</ruby>
|
264
|
-
|
265
|
-
h4. Sending Multipart Emails with Attachments
|
266
|
-
|
267
|
-
Once you use the +attachment+ method, ActionMailer will no longer automagically use the correct template based on the filename. You must declare which template you are using for each content type via the +part+ method.
|
268
|
-
|
269
|
-
In the following example, there would be two template files, +welcome_email_html.erb+ and +welcome_email_plain.erb+ in the +app/views/user_mailer+ folder.
|
270
|
-
|
271
|
-
<ruby>
|
272
|
-
class UserMailer < ActionMailer::Base
|
273
|
-
def welcome_email(user)
|
274
|
-
recipients user.email_address
|
275
|
-
subject "New account information"
|
276
|
-
from "system@example.com"
|
277
|
-
content_type "multipart/alternative"
|
278
|
-
|
279
|
-
part "text/html" do |p|
|
280
|
-
p.body = render_message("welcome_email_html", :message => "<h1>HTML content</h1>")
|
281
|
-
end
|
282
|
-
|
283
|
-
part "text/plain" do |p|
|
284
|
-
p.body = render_message("welcome_email_plain", :message => "text content")
|
285
|
-
end
|
286
|
-
|
287
|
-
attachment :content_type => "image/jpeg",
|
288
|
-
:body => File.read("an-image.jpg")
|
289
|
-
|
290
|
-
attachment "application/pdf" do |a|
|
291
|
-
a.body = generate_your_pdf_here()
|
292
|
-
end
|
293
|
-
end
|
294
|
-
end
|
295
|
-
</ruby>
|
296
|
-
|
297
|
-
h3. Receiving Emails
|
298
|
-
|
299
|
-
Receiving and parsing emails with Action Mailer can be a rather complex endeavour. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need:
|
300
|
-
|
301
|
-
1. Implement a +receive+ method in your mailer.
|
302
|
-
|
303
|
-
2. Configure your email server to forward emails from the address(es) you would like your app to receive to +/path/to/app/script/runner 'UserMailer.receive(STDIN.read)'+.
|
304
|
-
|
305
|
-
Once a method called +receive+ is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer +receive+ instance method. Here's an example:
|
306
|
-
|
307
|
-
<ruby>
|
308
|
-
class UserMailer < ActionMailer::Base
|
309
|
-
def receive(email)
|
310
|
-
page = Page.find_by_address(email.to.first)
|
311
|
-
page.emails.create(
|
312
|
-
:subject => email.subject,
|
313
|
-
:body => email.body
|
314
|
-
)
|
315
|
-
|
316
|
-
if email.has_attachments?
|
317
|
-
for attachment in email.attachments
|
318
|
-
page.attachments.create({
|
319
|
-
:file => attachment,
|
320
|
-
:description => email.subject
|
321
|
-
})
|
322
|
-
end
|
323
|
-
end
|
324
|
-
end
|
325
|
-
end
|
326
|
-
</ruby>
|
327
|
-
|
328
|
-
h3. Using Action Mailer Helpers
|
329
|
-
|
330
|
-
Action Mailer classes have 4 helper methods available to them:
|
331
|
-
|
332
|
-
|add_template_helper(helper_module)|Makes all the (instance) methods in the helper module available to templates rendered through this controller.|
|
333
|
-
|helper(*args, &block)| Declare a helper: helper :foo requires 'foo_helper' and includes FooHelper in the template class. helper FooHelper includes FooHelper in the template class. helper { def foo() "#{bar} is the very best" end } evaluates the block in the template class, adding method foo. helper(:three, BlindHelper) { def mice() 'mice' end } does all three. |
|
334
|
-
|helper_method| Declare a controller method as a helper. For example, helper_method :link_to def link_to(name, options) ... end makes the link_to controller method available in the view.|
|
335
|
-
|helper_attr| Declare a controller attribute as a helper. For example, helper_attr :name attr_accessor :name makes the name and name= controller methods available in the view. The is a convenience wrapper for helper_method.|
|
336
|
-
|
337
|
-
h3. Action Mailer Configuration
|
338
|
-
|
339
|
-
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
|
340
|
-
|
341
|
-
|template_root|Determines the base from which template references will be made.|
|
342
|
-
|logger|the logger is used for generating information on the mailing run if available. Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.|
|
343
|
-
|smtp_settings|Allows detailed configuration for :smtp delivery method: :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. :port - On the off chance that your mail server doesn't run on port 25, you can change it. :domain - If you need to specify a HELO domain, you can do it here. :user_name - If your mail server requires authentication, set the username in this setting. :password - If your mail server requires authentication, set the password in this setting. :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.|
|
344
|
-
|sendmail_settings|Allows you to override options for the :sendmail delivery method. :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. :arguments - The command line arguments. Defaults to -i -t.|
|
345
|
-
|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.|
|
346
|
-
|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.|
|
347
|
-
|perform_deliveries|Determines whether deliver_* methods are actually carried out. By default they are, but this can be turned off to help functional testing.|
|
348
|
-
|deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
|
349
|
-
|default_charset|The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also pick a different charset from inside a method with charset.|
|
350
|
-
|default_content_type|The default content type used for the main part of the message. Defaults to "text/plain". You can also pick a different content type from inside a method with content_type.|
|
351
|
-
|default_mime_version|The default mime version used for the message. Defaults to 1.0. You can also pick a different value from inside a method with mime_version.|
|
352
|
-
|default_implicit_parts_order|When a message is built implicitly (i.e. multiple parts are assembled from templates which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client and appear last in the mime encoded message. You can also pick a different order from inside a method with implicit_parts_order.|
|
353
|
-
|
354
|
-
|
355
|
-
h4. Example Action Mailer Configuration
|
356
|
-
|
357
|
-
An example would be:
|
358
|
-
|
359
|
-
<ruby>
|
360
|
-
ActionMailer::Base.delivery_method = :sendmail
|
361
|
-
ActionMailer::Base.sendmail_settings = {
|
362
|
-
:location => '/usr/sbin/sendmail',
|
363
|
-
:arguments => '-i -t'
|
364
|
-
}
|
365
|
-
ActionMailer::Base.perform_deliveries = true
|
366
|
-
ActionMailer::Base.raise_delivery_errors = true
|
367
|
-
ActionMailer::Base.default_charset = "iso-8859-1"
|
368
|
-
</ruby>
|
369
|
-
|
370
|
-
h4. Action Mailer Configuration for GMail
|
371
|
-
|
372
|
-
Instructions copied from http://http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html
|
373
|
-
|
374
|
-
First you must install the +action_mailer_tls+ plugin from http://code.openrain.com/rails/action_mailer_tls/, then all you have to do is configure action mailer.
|
375
|
-
|
376
|
-
<ruby>
|
377
|
-
ActionMailer::Base.smtp_settings = {
|
378
|
-
:address => "smtp.gmail.com",
|
379
|
-
:port => 587,
|
380
|
-
:domain => "domain.com",
|
381
|
-
:user_name => "user@domain.com",
|
382
|
-
:password => "password",
|
383
|
-
:authentication => :plain
|
384
|
-
}
|
385
|
-
</ruby>
|
386
|
-
|
387
|
-
h4. Configure Action Mailer to Recognize HAML Templates
|
388
|
-
|
389
|
-
In +config/environment.rb+, add the following line:
|
390
|
-
|
391
|
-
<ruby>
|
392
|
-
ActionMailer::Base.register_template_extension('haml')
|
393
|
-
</ruby>
|
394
|
-
|
395
|
-
h3. Mailer Testing
|
396
|
-
|
397
|
-
By default Action Mailer does not send emails in the test environment. They are just added to the +ActionMailer::Base.deliveries+ array.
|
398
|
-
|
399
|
-
Testing mailers normally involves two things: One is that the mail was queued, and the other one that the email is correct. With that in mind, we could test our example mailer from above like so:
|
400
|
-
|
401
|
-
<ruby>
|
402
|
-
class UserMailerTest < ActionMailer::TestCase
|
403
|
-
tests UserMailer
|
404
|
-
|
405
|
-
def test_welcome_email
|
406
|
-
user = users(:some_user_in_your_fixtures)
|
407
|
-
|
408
|
-
# Send the email, then test that it got queued
|
409
|
-
email = UserMailer.deliver_welcome_email(user)
|
410
|
-
assert !ActionMailer::Base.deliveries.empty?
|
411
|
-
|
412
|
-
# Test the body of the sent email contains what we expect it to
|
413
|
-
assert_equal [@user.email], email.to
|
414
|
-
assert_equal "Welcome to My Awesome Site", email.subject
|
415
|
-
assert_match /Welcome to example.com, #{user.first_name}/, email.body
|
416
|
-
end
|
417
|
-
end
|
418
|
-
</ruby>
|
419
|
-
|
420
|
-
In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect.
|
421
|
-
|
422
|
-
h3. Changelog
|
423
|
-
|
424
|
-
"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/25
|
@@ -1,135 +0,0 @@
|
|
1
|
-
h2. Active Record Basics
|
2
|
-
|
3
|
-
This guide will give you a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make you a stronger and better developer.
|
4
|
-
|
5
|
-
After reading this guide we hope that you'll be able to:
|
6
|
-
|
7
|
-
* Understand the way Active Record fits into the MVC model.
|
8
|
-
* Create basic Active Record models and map them with your database tables.
|
9
|
-
* Use your models to execute CRUD (Create, Read, Update and Delete) database operations.
|
10
|
-
* Follow the naming conventions used by Rails to make developing database applications easier and obvious.
|
11
|
-
* Take advantage of the way Active Record maps it's attributes with the database tables' columns to implement your application's logic.
|
12
|
-
* Use Active Record with legacy databases that do not follow the Rails naming conventions.
|
13
|
-
|
14
|
-
endprologue.
|
15
|
-
|
16
|
-
h3. What's Active Record?
|
17
|
-
|
18
|
-
Rails' ActiveRecord is an implementation of Martin Fowler's "Active Record Design Pattern":http://martinfowler.com/eaaCatalog/activeRecord.html. This pattern is based on the idea of creating relations between the database and the application in the following way:
|
19
|
-
|
20
|
-
* Each database table is mapped to a class.
|
21
|
-
* Each table column is mapped to an attribute of this class.
|
22
|
-
* Each instance of this class is mapped to a single row in the database table.
|
23
|
-
|
24
|
-
The definition of the Active Record pattern in Martin Fowler's words:
|
25
|
-
|
26
|
-
??An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.??
|
27
|
-
|
28
|
-
h3. Object Relational Mapping
|
29
|
-
|
30
|
-
The relation between databases and object-oriented software is called ORM, which is short for "Object Relational Mapping". The purpose of an ORM framework is to minimize the mismatch existent between relational databases and object-oriented software. In applications with a domain model, we have objects that represent both the state of the system and the behavior of the real world elements that were modeled through these objects. Since we need to store the system's state somehow, we can use relational databases, which are proven to be an excellent approach to data management. Usually this may become a very hard thing to do, since we need to create an object-oriented model of everything that lives in the database, from simple columns to complicated relations between different tables. Doing this kind of thing by hand is a tedious and error prone job. This is where an ORM framework comes in.
|
31
|
-
|
32
|
-
h3. ActiveRecord as an ORM Framework
|
33
|
-
|
34
|
-
ActiveRecord gives us several mechanisms, being the most important ones the ability to:
|
35
|
-
|
36
|
-
* Represent models.
|
37
|
-
* Represent associations between these models.
|
38
|
-
* Represent inheritance hierarchies through related models.
|
39
|
-
* Validate models before they get recorded to the database.
|
40
|
-
* Perform database operations in an object-oriented fashion.
|
41
|
-
|
42
|
-
It's easy to see that the Rails Active Record implementation goes way beyond the basic description of the Active Record Pattern.
|
43
|
-
|
44
|
-
h3. Active Record Inside the MVC Model
|
45
|
-
|
46
|
-
Active Record plays the role of model inside the MVC structure followed by Rails applications. Since model objects should encapsulate both state and logic of your applications, it's ActiveRecord responsibility to deliver you the easiest possible way to recover this data from the database.
|
47
|
-
|
48
|
-
h3. Convention over Configuration in ActiveRecord
|
49
|
-
|
50
|
-
When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating ActiveRecord models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can't follow the conventions for any reason.
|
51
|
-
|
52
|
-
h4. Naming Conventions
|
53
|
-
|
54
|
-
By default, ActiveRecord uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples:
|
55
|
-
|
56
|
-
* Database Table - Plural with underscores separating words i.e. (book_clubs)
|
57
|
-
* Model Class - Singular with the first letter of each word capitalized i.e. (BookClub)
|
58
|
-
|
59
|
-
|_.Model / Class |_.Table / Schema |
|
60
|
-
|Post |posts|
|
61
|
-
|LineItem |line_items|
|
62
|
-
|Deer |deer|
|
63
|
-
|Mouse |mice|
|
64
|
-
|Person |people|
|
65
|
-
|
66
|
-
|
67
|
-
h4. Schema Conventions
|
68
|
-
|
69
|
-
ActiveRecord uses naming conventions for the columns in database tables, depending on the purpose of these columns.
|
70
|
-
|
71
|
-
* *Foreign keys* - These fields should be named following the pattern table_id i.e. (item_id, order_id). These are the fields that ActiveRecord will look for when you create associations between your models.
|
72
|
-
* *Primary keys* - By default, ActiveRecord will use a integer column named "id" as the table's primary key. When using "Rails Migrations":http://guides.rails.info/migrations.html to create your tables, this column will be automatically created.
|
73
|
-
|
74
|
-
There are also some optional column names that will create additional features to ActiveRecord instances:
|
75
|
-
|
76
|
-
* *created_at / created_on* - ActiveRecord will store the current date and time to this field when creating the record.
|
77
|
-
* *updated_at / updated_on* - ActiveRecord will store the current date and times to this field when updating the record.
|
78
|
-
* *lock_version* - Adds "optimistic locking":http://api.rubyonrails.com/classes/ActiveRecord/Locking.html to a model.
|
79
|
-
* *type* - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.com/classes/ActiveRecord/Base.html
|
80
|
-
* *(table_name)_count* - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.
|
81
|
-
|
82
|
-
NOTE: While these column names are optional they are in fact reserved by ActiveRecord. Steer clear of reserved keywords unless you want the extra functionality. For example, "type" is a reserved keyword used to designate a table using Single Table Inheritance. If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
|
83
|
-
|
84
|
-
h3. Creating ActiveRecord Models
|
85
|
-
|
86
|
-
It's very easy to create ActiveRecord models. All you have to do is to subclass the ActiveRecord::Base class and you're good to go:
|
87
|
-
|
88
|
-
<ruby>
|
89
|
-
class Product < ActiveRecord::Base; end
|
90
|
-
</ruby>
|
91
|
-
|
92
|
-
This will create a +Product+ model, mapped to a *products* table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. So, suppose that the *products* table was created using a SQL sentence like:
|
93
|
-
|
94
|
-
<sql>
|
95
|
-
CREATE TABLE products (
|
96
|
-
id int(11) NOT NULL auto_increment,
|
97
|
-
name varchar(255),
|
98
|
-
PRIMARY KEY (id)
|
99
|
-
);
|
100
|
-
</sql>
|
101
|
-
|
102
|
-
Following the table schema above, you would be able to write code like the following:
|
103
|
-
|
104
|
-
<ruby>
|
105
|
-
p = Product.new
|
106
|
-
p.name = "Some Book"
|
107
|
-
puts p.name # "Some Book"
|
108
|
-
</ruby>
|
109
|
-
|
110
|
-
h3. Overriding the Naming Conventions
|
111
|
-
|
112
|
-
What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
|
113
|
-
|
114
|
-
You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
|
115
|
-
<ruby>
|
116
|
-
class Product < ActiveRecord::Base
|
117
|
-
set_table_name "PRODUCT"
|
118
|
-
end
|
119
|
-
</ruby>
|
120
|
-
|
121
|
-
It's also possible to override the column that should be used as the table's primary key. Use the +ActiveRecord::Base.set_primary_key+ method for that:
|
122
|
-
<ruby>
|
123
|
-
class Product < ActiveRecord::Base
|
124
|
-
set_primary_key "product_id"
|
125
|
-
end
|
126
|
-
</ruby>
|
127
|
-
|
128
|
-
h3. Validations
|
129
|
-
|
130
|
-
ActiveRecord gives the ability to validate the state of your models before they get recorded into the database. There are several methods that you can use to hook into the life-cycle of your models and validate that an attribute value is not empty or follow a specific format and so on. You can learn more about validations in the "Active Record Validations and Callbacks guide":http://guides.rails.info/activerecord_validations_callbacks.html#_overview_of_activerecord_validation.
|
131
|
-
|
132
|
-
h3. Callbacks
|
133
|
-
|
134
|
-
ActiveRecord callbacks allow you to attach code to certain events in the life-cycle of your models. This way you can add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":http://guides.rails.info/activerecord_validations_callbacks.html#_callbacks.
|
135
|
-
|