Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 1900 lines (1716 sloc) 85.716 kb
db045db @dhh Initial
dhh authored
1 require 'yaml'
aabf909 @jeremy Correct reader method generation for primary key attribute: handle case ...
jeremy authored
2 require 'set'
a15e02d @josevalim Unify benchmark APIs.
josevalim authored
3 require 'active_support/benchmarkable'
f5d720f @jeremy Opt in to Dependencies
jeremy authored
4 require 'active_support/dependencies'
033e0a0 @josevalim ActiveRecord and ActionPack now use the new descendants implementation.
josevalim authored
5 require 'active_support/descendants_tracker'
5f222c5 @jeremy Remove 'core' fluff. Hookable ActiveSupport.load_all!
jeremy authored
6 require 'active_support/time'
bab1f91 @phs table_name_prefix and table_name_suffix are class_attributes instead of ...
phs authored
7 require 'active_support/core_ext/class/attribute'
e8550ee @jeremy Cherry-pick core extensions
jeremy authored
8 require 'active_support/core_ext/class/attribute_accessors'
9 require 'active_support/core_ext/class/delegating_attributes'
10 require 'active_support/core_ext/class/inheritable_attributes'
11 require 'active_support/core_ext/array/extract_options'
12 require 'active_support/core_ext/hash/deep_merge'
13 require 'active_support/core_ext/hash/indifferent_access'
14 require 'active_support/core_ext/hash/slice'
15 require 'active_support/core_ext/string/behavior'
89978f1 @fxn moves Object#singleton_class to Kernel#singleton_class to match Ruby als...
fxn authored
16 require 'active_support/core_ext/kernel/singleton_class'
a7fd564 @lifo Add Model.select/group/order/limit/joins/conditions/preload/eager_load c...
lifo authored
17 require 'active_support/core_ext/module/delegation'
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
18 require 'active_support/core_ext/module/introspection'
105f9b8 @fxn adds missing requires for Object#duplicable?
fxn authored
19 require 'active_support/core_ext/object/duplicable'
76f024a @fxn adds missing requires for Object#blank? and Object#present?
fxn authored
20 require 'active_support/core_ext/object/blank'
39d6f9e @wycats Make many parts of Rails lazy. In order to facilitate this,
wycats authored
21 require 'arel'
22 require 'active_record/errors'
db045db @dhh Initial
dhh authored
23
24 module ActiveRecord #:nodoc:
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
25 # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
db045db @dhh Initial
dhh authored
26 # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
27 # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
28 # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
29 #
db045db @dhh Initial
dhh authored
30 # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
31 #
db045db @dhh Initial
dhh authored
32 # == Creation
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
33 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
34 # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
35 # you're receiving the data from somewhere else, like an HTTP request. It works like this:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
36 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the examples h...
dhh authored
37 # user = User.new(:name => "David", :occupation => "Code Artist")
db045db @dhh Initial
dhh authored
38 # user.name # => "David"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
39 #
db045db @dhh Initial
dhh authored
40 # You can also use block initialization:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
41 #
db045db @dhh Initial
dhh authored
42 # user = User.new do |u|
43 # u.name = "David"
44 # u.occupation = "Code Artist"
45 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
46 #
db045db @dhh Initial
dhh authored
47 # And of course you can just create a bare object and specify the attributes after the fact:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
48 #
db045db @dhh Initial
dhh authored
49 # user = User.new
50 # user.name = "David"
51 # user.occupation = "Code Artist"
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
52 #
db045db @dhh Initial
dhh authored
53 # == Conditions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
54 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
55 # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
db045db @dhh Initial
dhh authored
56 # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
57 # be used for statements that don't involve tainted data. The hash form works much like the array form, except
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #697...
jeremy authored
58 # only equality and range is possible. Examples:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
59 #
48052d7 @jeremy to_xml fixes, features, and speedup. Closes #4989.
jeremy authored
60 # class User < ActiveRecord::Base
db045db @dhh Initial
dhh authored
61 # def self.authenticate_unsafely(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
62 # where("user_name = '#{user_name}' AND password = '#{password}'").first
db045db @dhh Initial
dhh authored
63 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
64 #
db045db @dhh Initial
dhh authored
65 # def self.authenticate_safely(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
66 # where("user_name = ? AND password = ?", user_name, password).first
db045db @dhh Initial
dhh authored
67 # end
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
68 #
69 # def self.authenticate_safely_simply(user_name, password)
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
70 # where(:user_name => user_name, :password => password).first
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
71 # end
db045db @dhh Initial
dhh authored
72 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
73 #
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
74 # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
75 # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
76 # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
77 # which will ensure that an attacker can't escape the query and fake the login (or worse).
2575b3b @dhh Added extra words of caution for guarding against SQL-injection attacks
dhh authored
78 #
5cd38ca @dhh Added documentation about named bind variables
dhh authored
79 # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
80 # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
5cd38ca @dhh Added documentation about named bind variables
dhh authored
81 # the question marks with symbols and supplying a hash with values for the matching symbol keys:
82 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
83 # Company.where(
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
84 # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
5cd38ca @dhh Added documentation about named bind variables
dhh authored
85 # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
86 # ).first
5cd38ca @dhh Added documentation about named bind variables
dhh authored
87 #
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
88 # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
89 # operator. For instance:
90 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
91 # Student.where(:first_name => "Harvey", :status => 1)
92 # Student.where(params[:student])
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
93 #
2876707 @jeremy Pass a range in :conditions to use the SQL BETWEEN operator. Closes #697...
jeremy authored
94 # A range may be used in the hash to use the SQL BETWEEN operator:
95 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
96 # Student.where(:grade => 9..12)
c5ec16e @dhh Added simple hash conditions to find that'll just convert hash to an AND...
dhh authored
97 #
aa4af60 @lifo Improve documentation.
lifo authored
98 # An array may be used in the hash to use the SQL IN operator:
99 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
100 # Student.where(:grade => [9,11,12])
aa4af60 @lifo Improve documentation.
lifo authored
101 #
e033b5d @lifo Merge docrails
lifo authored
102 # When joining tables, nested hashes or keys written in the form 'table_name.column_name' can be used to qualify the table name of a
103 # particular condition. For instance:
104 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
105 # Student.joins(:schools).where(:schools => { :type => 'public' })
106 # Student.joins(:schools).where('schools.type' => 'public' )
e033b5d @lifo Merge docrails
lifo authored
107 #
db045db @dhh Initial
dhh authored
108 # == Overwriting default accessors
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
109 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
110 # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
111 # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
98dc582 @lifo Merge docrails.
lifo authored
112 # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
db045db @dhh Initial
dhh authored
113 # Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
114 #
db045db @dhh Initial
dhh authored
115 # class Song < ActiveRecord::Base
116 # # Uses an integer of seconds to hold the length of the song
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
117 #
db045db @dhh Initial
dhh authored
118 # def length=(minutes)
64092de @fxn Improve documentation coverage and markup
fxn authored
119 # write_attribute(:length, minutes.to_i * 60)
db045db @dhh Initial
dhh authored
120 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
121 #
db045db @dhh Initial
dhh authored
122 # def length
0591c53 @dhh Made the dynamic finders use the new find API and updated the examples h...
dhh authored
123 # read_attribute(:length) / 60
db045db @dhh Initial
dhh authored
124 # end
125 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
126 #
98dc582 @lifo Merge docrails.
lifo authored
127 # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
128 # <tt>read_attribute(:attribute)</tt> as a shorter form.
0591c53 @dhh Made the dynamic finders use the new find API and updated the examples h...
dhh authored
129 #
e4d845e Document automatically generated predicate methods for attributes. Close...
Marcel Molina authored
130 # == Attribute query methods
131 #
132 # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
133 # Query methods allow you to test whether an attribute value is present.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
134 #
e4d845e Document automatically generated predicate methods for attributes. Close...
Marcel Molina authored
135 # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
136 # to determine whether the user has a name:
137 #
138 # user = User.new(:name => "David")
139 # user.name? # => true
140 #
141 # anonymous = User.new(:name => "")
142 # anonymous.name? # => false
143 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
144 # == Accessing attributes before they have been typecasted
4eab375 @dhh Finished polishing API docs
dhh authored
145 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
146 # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
dc4eec1 @lifo Merge docrails:
lifo authored
147 # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
98dc582 @lifo Merge docrails.
lifo authored
148 # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
4eab375 @dhh Finished polishing API docs
dhh authored
149 #
150 # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
151 # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
4eab375 @dhh Finished polishing API docs
dhh authored
152 # want.
153 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
154 # == Dynamic attribute-based finders
155 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
156 # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
6dc9173 @dhh Missing doc updates
dhh authored
157 # appending the name of an attribute to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>,
98dc582 @lifo Merge docrails.
lifo authored
158 # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
159 # <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
160 # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
161 #
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
162 # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
163 # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
164 # <tt>Person.where(:user_name => user_name, :password => password).first</tt>, you just do
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
165 # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
166 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
167 # It's even possible to call these dynamic finder methods on relations and named scopes. For example :
168 #
169 # Payment.order("created_on").find_all_by_amount(50)
170 # Payment.pending.find_last_by_amount(100)
959f362 @dhh Added find_all style to the new dynamic finders
dhh authored
171 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
172 # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
5c47ceb @NZKoz Typo fix in documentation from [9090] References #11422
NZKoz authored
173 # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
174 #
175 # # No 'Summer' tag exists
176 # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
177 #
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
178 # # Now the 'Summer' tag does exist
179 # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
180 #
c10b225 @dhh Fixed that ActiveRecord#Base.find_or_create/initialize would not honor a...
dhh authored
181 # # Now 'Bob' exist and is an 'admin'
182 # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
183 #
0432d15 @lifo Merge with docrails.
lifo authored
184 # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be set unless they are given in a block. For example:
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X but d...
sstephenson authored
185 #
186 # # No 'Winter' tag exists
187 # winter = Tag.find_or_initialize_by_name("Winter")
85fbb22 @dhh Backed out of new_record? to new? transformation as it would screw up ex...
dhh authored
188 # winter.new_record? # true
d19e464 @sstephenson Added find_or_initialize_by_X which works like find_or_create_by_X but d...
sstephenson authored
189 #
14cc8d2 @jeremy find_or_create_by_* takes a hash so you can create with more attributes ...
jeremy authored
190 # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
191 # a list of parameters. For example:
192 #
193 # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
194 #
195 # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
196 #
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
197 # == Saving arrays, hashes, and other non-mappable objects in text columns
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
198 #
199 # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
200 # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
201 #
db045db @dhh Initial
dhh authored
202 # class User < ActiveRecord::Base
203 # serialize :preferences
204 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
205 #
ca2eb16 Fix syntax error in documentation. Closes #4679. [mislav@nippur.irb.hr]
Marcel Molina authored
206 # user = User.create(:preferences => { "background" => "black", "display" => large })
db045db @dhh Initial
dhh authored
207 # User.find(user.id).preferences # => { "background" => "black", "display" => large }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
208 #
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
209 # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
39e1ac6 @lifo Merge docrails
lifo authored
210 # descendant of a class not in the hierarchy. Example:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
211 #
db045db @dhh Initial
dhh authored
212 # class User < ActiveRecord::Base
66f44e6 @dhh Updated documentation for serialize
dhh authored
213 # serialize :preferences, Hash
db045db @dhh Initial
dhh authored
214 # end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
215 #
0591c53 @dhh Made the dynamic finders use the new find API and updated the examples h...
dhh authored
216 # user = User.create(:preferences => %w( one two three ))
db045db @dhh Initial
dhh authored
217 # User.find(user.id).preferences # raises SerializationTypeMismatch
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
218 #
db045db @dhh Initial
dhh authored
219 # == Single table inheritance
220 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
221 # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
db045db @dhh Initial
dhh authored
222 # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
223 #
224 # class Company < ActiveRecord::Base; end
225 # class Firm < Company; end
226 # class Client < Company; end
227 # class PriorityClient < Client; end
228 #
98dc582 @lifo Merge docrails.
lifo authored
229 # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
230 # fetch this row again using <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
db045db @dhh Initial
dhh authored
231 #
f033833 @dhh Improving documentation...
dhh authored
232 # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
233 # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
234 #
db045db @dhh Initial
dhh authored
235 # Note, all the attributes for all the cases are kept in the same table. Read more:
236 # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
237 #
db045db @dhh Initial
dhh authored
238 # == Connection to multiple databases in different models
239 #
240 # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
241 # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
98dc582 @lifo Merge docrails.
lifo authored
242 # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
243 # and Course and all of its subclasses will use this connection instead.
db045db @dhh Initial
dhh authored
244 #
245 # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
246 # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
247 #
248 # == Exceptions
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
249 #
dc4eec1 @lifo Merge docrails:
lifo authored
250 # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
251 # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
db045db @dhh Initial
dhh authored
252 # <tt>:adapter</tt> key.
dc4eec1 @lifo Merge docrails:
lifo authored
253 # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
254 # (or a bad spelling of an existing one).
dc4eec1 @lifo Merge docrails:
lifo authored
255 # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
256 # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
257 # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
258 # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
259 # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
260 # nothing was found, please check its documentation for further details.
261 # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
262 # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
263 # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError except...
dhh authored
264 # objects that should be inspected to determine which attributes triggered the errors.
dc4eec1 @lifo Merge docrails:
lifo authored
265 # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
d2fefbe @dhh Added MultiparameterAssignmentErrors and AttributeAssignmentError except...
dhh authored
266 # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
5707027 @dhh Added better exception error when unknown column types are used with mig...
dhh authored
267 #
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
268 # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
dc4eec1 @lifo Merge docrails:
lifo authored
269 # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
db045db @dhh Initial
dhh authored
270 # instances in the current object space.
271 class Base
0905396 @miloops construct_finder_sql now use Arel
miloops authored
272 ##
dbbae5e @lifo Merge with docrails
lifo authored
273 # :singleton-method:
db045db @dhh Initial
dhh authored
274 # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
275 # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
276 cattr_accessor :logger, :instance_writer => false
e694114 @jeremy Deprecation: removed Reloadable.
jeremy authored
277
dbbae5e @lifo Merge with docrails
lifo authored
278 ##
279 # :singleton-method:
a293278 @lifo Merge docrails
lifo authored
280 # Contains the database configuration - as is typically stored in config/database.yml -
281 # as a Hash.
282 #
283 # For example, the following database.yml...
0905396 @miloops construct_finder_sql now use Arel
miloops authored
284 #
a293278 @lifo Merge docrails
lifo authored
285 # development:
286 # adapter: sqlite3
287 # database: db/development.sqlite3
0905396 @miloops construct_finder_sql now use Arel
miloops authored
288 #
a293278 @lifo Merge docrails
lifo authored
289 # production:
290 # adapter: sqlite3
291 # database: db/production.sqlite3
292 #
293 # ...would result in ActiveRecord::Base.configurations to look like this:
294 #
295 # {
296 # 'development' => {
297 # 'adapter' => 'sqlite3',
298 # 'database' => 'db/development.sqlite3'
299 # },
300 # 'production' => {
301 # 'adapter' => 'sqlite3',
302 # 'database' => 'db/production.sqlite3'
303 # }
304 # }
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
305 cattr_accessor :configurations, :instance_writer => false
c4a3634 @jeremy Corrected @@configurations typo. #1410 [david@ruppconsulting.com]
jeremy authored
306 @@configurations = {}
307
dbbae5e @lifo Merge with docrails
lifo authored
308 ##
309 # :singleton-method:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
310 # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
db045db @dhh Initial
dhh authored
311 # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
312 # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
313 # that this is a global setting for all Active Records.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
314 cattr_accessor :primary_key_prefix_type, :instance_writer => false
db045db @dhh Initial
dhh authored
315 @@primary_key_prefix_type = nil
316
dbbae5e @lifo Merge with docrails
lifo authored
317 ##
318 # :singleton-method:
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
319 # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
320 # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
db045db @dhh Initial
dhh authored
321 # for tables in a shared database. By default, the prefix is the empty string.
67d1cec @pixeltrix Add the ability to specify table_name_prefix on individual modules
pixeltrix authored
322 #
323 # If you are organising your models within modules you can add a prefix to the models within a namespace by defining
324 # a singleton method in the parent module called table_name_prefix which returns your chosen prefix.
bab1f91 @phs table_name_prefix and table_name_suffix are class_attributes instead of ...
phs authored
325 class_attribute :table_name_prefix, :instance_writer => false
326 self.table_name_prefix = ""
db045db @dhh Initial
dhh authored
327
dbbae5e @lifo Merge with docrails
lifo authored
328 ##
329 # :singleton-method:
db045db @dhh Initial
dhh authored
330 # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
331 # "people_basecamp"). By default, the suffix is the empty string.
bab1f91 @phs table_name_prefix and table_name_suffix are class_attributes instead of ...
phs authored
332 class_attribute :table_name_suffix, :instance_writer => false
333 self.table_name_suffix = ""
db045db @dhh Initial
dhh authored
334
dbbae5e @lifo Merge with docrails
lifo authored
335 ##
336 # :singleton-method:
84a14f2 @jeremy Raise ProtectedAttributeAssignmentError in development and test environm...
jeremy authored
337 # Indicates whether table names should be the pluralized versions of the corresponding class names.
98dc582 @lifo Merge docrails.
lifo authored
338 # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
db045db @dhh Initial
dhh authored
339 # See table_name for the full rules on table/class naming. This is true, by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
340 cattr_accessor :pluralize_table_names, :instance_writer => false
db045db @dhh Initial
dhh authored
341 @@pluralize_table_names = true
342
dbbae5e @lifo Merge with docrails
lifo authored
343 ##
344 # :singleton-method:
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use Time...
dhh authored
345 # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
346 # This is set to :local by default.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
347 cattr_accessor :default_timezone, :instance_writer => false
60de8c1 @dhh Added Base.default_timezone accessor that determines whether to use Time...
dhh authored
348 @@default_timezone = :local
d8641ca @jeremy CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Mos...
jeremy authored
349
dbbae5e @lifo Merge with docrails
lifo authored
350 ##
351 # :singleton-method:
24c3599 @sstephenson Support using different database adapters for development and test with ...
sstephenson authored
352 # Specifies the format to use when dumping the database schema with Rails'
353 # Rakefile. If :sql, the schema is dumped as (potentially database-
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
354 # specific) SQL statements. If :ruby, the schema is dumped as an
24c3599 @sstephenson Support using different database adapters for development and test with ...
sstephenson authored
355 # ActiveRecord::Schema file which can be loaded into any database that
356 # supports migrations. Use :ruby if you want to have different database
357 # adapters for, e.g., your development and test environments.
1a11bff @technoweenie Don't create instance writer methods for class attributes. Closes #7401...
technoweenie authored
358 cattr_accessor :schema_format , :instance_writer => false
660952e @dhh CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by defaul...
dhh authored
359 @@schema_format = :ruby
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
360
dbbae5e @lifo Merge with docrails
lifo authored
361 ##
362 # :singleton-method:
155f0be @rizwanreza Changes migration number to version due to ambiguity. [#3065 state:commi...
rizwanreza authored
363 # Specify whether or not to use timestamps for migration versions
bbab639 @nikz Set config.active_record.timestamped_migrations = false to have migratio...
nikz authored
364 cattr_accessor :timestamped_migrations , :instance_writer => false
365 @@timestamped_migrations = true
366
bca8751 @divoxx Add ActiveRecord option to store the full class name on STI's type colum...
divoxx authored
367 # Determine whether to store the full constant name including namespace when using STI
368 superclass_delegating_accessor :store_full_sti_class
1459c8c @dhh Changed ActiveRecord::Base.store_full_sti_class to be true by default re...
dhh authored
369 self.store_full_sti_class = true
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
370
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
371 # Stores the default scope for the class
372 class_inheritable_accessor :default_scoping, :instance_writer => false
373 self.default_scoping = []
374
db045db @dhh Initial
dhh authored
375 class << self # Class methods
8d78a82 @josevalim Deprecate ActiveRecord::Base.colorize_logging.
josevalim authored
376 def colorize_logging(*args)
377 ActiveSupport::Deprecation.warn "ActiveRecord::Base.colorize_logging and " <<
39d6f9e @wycats Make many parts of Rails lazy. In order to facilitate this,
wycats authored
378 "config.active_record.colorize_logging are deprecated. Please use " <<
f0523f7 @sikachu Rename Rails::Subscriber to Rails::LogSubscriber
sikachu authored
379 "Rails::LogSubscriber.colorize_logging or config.colorize_logging instead", caller
8d78a82 @josevalim Deprecate ActiveRecord::Base.colorize_logging.
josevalim authored
380 end
381 alias :colorize_logging= :colorize_logging
382
8d31c9f @lifo Move update and update_all to Relation
lifo authored
383 delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
dc3cc6c @lifo Move batch finders to Relation
lifo authored
384 delegate :find_each, :find_in_batches, :to => :scoped
6f5f23a @lifo Add Relation#includes to be an equivalent of current finder option :incl...
lifo authored
385 delegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
9465b84 @lifo Rename CalculationMethods to Calculations and get rid of the old Calcula...
lifo authored
386 delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
a7fd564 @lifo Add Model.select/group/order/limit/joins/conditions/preload/eager_load c...
lifo authored
387
98dc582 @lifo Merge docrails.
lifo authored
388 # Executes a custom SQL query against your database and returns all the results. The results will
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
389 # be returned as an array with columns requested encapsulated as attributes of the model you call
a293278 @lifo Merge docrails
lifo authored
390 # this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
391 # a Product object with the attributes you specified in the SQL query.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
392 #
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
393 # If you call a complicated SQL query which spans multiple tables the columns specified by the
394 # SELECT will be attributes of the model, whether or not they are columns of the corresponding
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
395 # table.
396 #
98dc582 @lifo Merge docrails.
lifo authored
397 # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
398 # no database agnostic conversions performed. This should be a last resort because using, for example,
399 # MySQL specific terms will lock you to using that particular database engine or require you to
a293278 @lifo Merge docrails
lifo authored
400 # change your call if you switch engines.
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
401 #
402 # ==== Examples
98dc582 @lifo Merge docrails.
lifo authored
403 # # A simple SQL query spanning multiple tables
edf32ce More complete documentation for find_by_sql. Closes #7912 [fearoffish]
Marcel Molina authored
404 # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
405 # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
406 #
407 # # You can use the same string replacement techniques as you can with ActiveRecord#find
408 # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
409 # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
db045db @dhh Initial
dhh authored
410 def find_by_sql(sql)
6e3d2a7 @jeremy Revert "Performance: freeze cached rows instead of duping"
jeremy authored
411 connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
db045db @dhh Initial
dhh authored
412 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
413
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
414 # Creates an object (or multiple objects) and saves it to the database, if validations pass.
a23bea7 Document API for create's attributes parameter and provide examples. Clo...
Marcel Molina authored
415 # The resulting object is returned whether the object was saved successfully to the database or not.
416 #
417 # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
418 # attributes on the objects that are to be created.
419 #
420 # ==== Examples
421 # # Create a single new object
422 # User.create(:first_name => 'Jamie')
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
423 #
a23bea7 Document API for create's attributes parameter and provide examples. Clo...
Marcel Molina authored
424 # # Create an Array of new objects
dc4eec1 @lifo Merge docrails:
lifo authored
425 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
426 #
427 # # Create a single object and pass it into a block to set other attributes.
428 # User.create(:first_name => 'Jamie') do |u|
429 # u.is_admin = false
430 # end
431 #
432 # # Creating an Array of new objects using a block, where the block is executed for each object:
dc4eec1 @lifo Merge docrails:
lifo authored
433 # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
434 # u.is_admin = false
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
435 # end
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
436 def create(attributes = nil, &block)
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
437 if attributes.is_a?(Array)
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
438 attributes.collect { |attr| create(attr, &block) }
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
439 else
440 object = new(attributes)
dd120ed @dhh Added block-setting of attributes for Base.create like Base.new already ...
dhh authored
441 yield(object) if block_given?
efa81da @dhh Added the option of supplying an array of ids and attributes to Base#upd...
dhh authored
442 object.save
443 object
444 end
db045db @dhh Initial
dhh authored
445 end
446
447 # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
448 # The use of this method should be restricted to complicated SQL queries that can't be executed
ee614d6 Add documentation caveat about when to use count_by_sql. Closes #8090. [...
Marcel Molina authored
449 # using the ActiveRecord::Calculations class methods. Look into those before using this.
450 #
a293278 @lifo Merge docrails
lifo authored
451 # ==== Parameters
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
452 #
dc4eec1 @lifo Merge docrails:
lifo authored
453 # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
ee614d6 Add documentation caveat about when to use count_by_sql. Closes #8090. [...
Marcel Molina authored
454 #
455 # ==== Examples
456 #
e17bf81 @jamis Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
jamis authored
457 # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
db045db @dhh Initial
dhh authored
458 def count_by_sql(sql)
a775cb1 @dhh Added the option for sanitizing find_by_sql and the offset parts in regu...
dhh authored
459 sql = sanitize_conditions(sql)
caaf40d @dhh Added AbstractAdapter#select_value and AbstractAdapter#select_values as ...
dhh authored
460 connection.select_value(sql, "#{name} Count").to_i
db045db @dhh Initial
dhh authored
461 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
462
98dc582 @lifo Merge docrails.
lifo authored
463 # Attributes named in this macro are protected from mass-assignment,
464 # such as <tt>new(attributes)</tt>,
465 # <tt>update_attributes(attributes)</tt>, or
466 # <tt>attributes=(attributes)</tt>.
467 #
468 # Mass-assignment to these attributes will simply be ignored, to assign
469 # to them you can use direct writer methods. This is meant to protect
470 # sensitive attributes from being overwritten by malicious users
471 # tampering with URLs or forms.
db045db @dhh Initial
dhh authored
472 #
473 # class Customer < ActiveRecord::Base
474 # attr_protected :credit_rating
475 # end
476 #
477 # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
478 # customer.credit_rating # => nil
479 # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
480 # customer.credit_rating # => nil
481 #
482 # customer.credit_rating = "Average"
483 # customer.credit_rating # => "Average"
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
484 #
98dc582 @lifo Merge docrails.
lifo authored
485 # To start from an all-closed default and enable attributes as needed,
486 # have a look at +attr_accessible+.
e033b5d @lifo Merge docrails
lifo authored
487 #
488 # If the access logic of your application is richer you can use <tt>Hash#except</tt>
489 # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
490 # passed to Active Record.
31c8353 @miloops Don't use local vars before testing its conditional.
miloops authored
491 #
e033b5d @lifo Merge docrails
lifo authored
492 # For example, it could be the case that the list of protected attributes
493 # for a given model depends on the role of the user:
494 #
495 # # Assumes plan_id is not protected because it depends on the role.
496 # params[:account] = params[:account].except(:plan_id) unless admin?
497 # @account.update_attributes(params[:account])
498 #
499 # Note that +attr_protected+ is still applied to the received hash. Thus,
500 # with this technique you can at most _extend_ the list of protected
501 # attributes for a particular mass-assignment call.
db045db @dhh Initial
dhh authored
502 def attr_protected(*attributes)
b6bac73 Merge commit 'origin/master'
Yehuda Katz + Carl Lerche authored
503 write_inheritable_attribute(:attr_protected, Set.new(attributes.map {|a| a.to_s}) + (protected_attributes || []))
db045db @dhh Initial
dhh authored
504 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
505
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
506 # Returns an array of all the attributes that have been protected from mass-assignment.
db045db @dhh Initial
dhh authored
507 def protected_attributes # :nodoc:
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored
508 read_inheritable_attribute(:attr_protected)
db045db @dhh Initial
dhh authored
509 end
510
98dc582 @lifo Merge docrails.
lifo authored
511 # Specifies a white list of model attributes that can be set via
512 # mass-assignment, such as <tt>new(attributes)</tt>,
513 # <tt>update_attributes(attributes)</tt>, or
514 # <tt>attributes=(attributes)</tt>
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
515 #
98dc582 @lifo Merge docrails.
lifo authored
516 # This is the opposite of the +attr_protected+ macro: Mass-assignment
517 # will only set attributes in this list, to assign to the rest of
518 # attributes you can use direct writer methods. This is meant to protect
519 # sensitive attributes from being overwritten by malicious users
520 # tampering with URLs or forms. If you'd rather start from an all-open
521 # default and restrict attributes as needed, have a look at
522 # +attr_protected+.
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
523 #
524 # class Customer < ActiveRecord::Base
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
525 # attr_accessible :name, :nickname
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
526 # end
527 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
528 # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
529 # customer.credit_rating # => nil
530 # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
531 # customer.credit_rating # => nil
d761ac4 Add docs explaining how to protect all attributes using attr_accessible ...
Marcel Molina authored
532 #
f770b82 Enhance explanation with more examples for attr_accessible macro. Closes...
Marcel Molina authored
533 # customer.credit_rating = "Average"
534 # customer.credit_rating # => "Average"
e033b5d @lifo Merge docrails
lifo authored
535 #
536 # If the access logic of your application is richer you can use <tt>Hash#except</tt>
537 # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
538 # passed to Active Record.
31c8353 @miloops Don't use local vars before testing its conditional.
miloops authored
539 #
e033b5d @lifo Merge docrails
lifo authored
540 # For example, it could be the case that the list of accessible attributes
541 # for a given model depends on the role of the user:
542 #
543 # # Assumes plan_id is accessible because it depends on the role.
544 # params[:account] = params[:account].except(:plan_id) unless admin?
545 # @account.update_attributes(params[:account])
546 #
547 # Note that +attr_accessible+ is still applied to the received hash. Thus,
548 # with this technique you can at most _narrow_ the list of accessible
549 # attributes for a particular mass-assignment call.
db045db @dhh Initial
dhh authored
550 def attr_accessible(*attributes)
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored
551 write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
db045db @dhh Initial
dhh authored
552 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
553
098fa94 @dhh Fixed documentation snafus #575, #576, #577, #585
dhh authored
554 # Returns an array of all the attributes that have been made accessible to mass-assignment.
db045db @dhh Initial
dhh authored
555 def accessible_attributes # :nodoc:
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored
556 read_inheritable_attribute(:attr_accessible)
db045db @dhh Initial
dhh authored
557 end
558
66d05f5 @technoweenie Add attr_readonly to specify columns that are skipped during a normal Ac...
technoweenie authored
559 # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
560 def attr_readonly(*attributes)
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored
561 write_inheritable_attribute(:attr_readonly, Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
66d05f5 @technoweenie Add attr_readonly to specify columns that are skipped during a normal Ac...
technoweenie authored
562 end
563
564 # Returns an array of all the attributes that have been specified as readonly.
565 def readonly_attributes
5b61168 @miloops Added arel_attributes_values methods, refactored locking and AR#update t...
miloops authored
566 read_inheritable_attribute(:attr_readonly) || []
66d05f5 @technoweenie Add attr_readonly to specify columns that are skipped during a normal Ac...
technoweenie authored
567 end
c450a36 @dhh Doc fixes
dhh authored
568
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
569 # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
570 # then specify the name of that attribute using this method and it will be handled automatically.
571 # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
98dc582 @lifo Merge docrails.
lifo authored
572 # class on retrieval or SerializationTypeMismatch will be raised.
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
573 #
a293278 @lifo Merge docrails
lifo authored
574 # ==== Parameters
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
575 #
dc4eec1 @lifo Merge docrails:
lifo authored
576 # * +attr_name+ - The field name that should be serialized.
577 # * +class_name+ - Optional, class name that the object type should be equal to.
1a0cdf7 @dhh Docfix (closes #8096)
dhh authored
578 #
579 # ==== Example
580 # # Serialize a preferences attribute
581 # class User
582 # serialize :preferences
583 # end
db045db @dhh Initial
dhh authored
584 def serialize(attr_name, class_name = Object)
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
585 serialized_attributes[attr_name.to_s] = class_name
db045db @dhh Initial
dhh authored
586 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
587
db045db @dhh Initial
dhh authored
588 # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
589 def serialized_attributes
288e947 @clemens Some performance goodness for inheritable attributes.
clemens authored
590 read_inheritable_attribute(:attr_serialized) or write_inheritable_attribute(:attr_serialized, {})
db045db @dhh Initial
dhh authored
591 end
592
593 # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
98dc582 @lifo Merge docrails.
lifo authored
594 # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used
d64832c Give examples for what tables should be called for models inside a modul...
Marcel Molina authored
595 # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
596 # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
db045db @dhh Initial
dhh authored
597 #
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of th...
jeremy authored
598 # Nested classes are given table names prefixed by the singular form of
98dc582 @lifo Merge docrails.
lifo authored
599 # the parent's table name. Enclosing modules are not considered.
600 #
601 # ==== Examples
d64832c Give examples for what tables should be called for models inside a modul...
Marcel Molina authored
602 #
603 # class Invoice < ActiveRecord::Base; end;
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of th...
jeremy authored
604 # file class table_name
605 # invoice.rb Invoice invoices
d64832c Give examples for what tables should be called for models inside a modul...
Marcel Molina authored
606 #
607 # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end;
608 # file class table_name
609 # invoice.rb Invoice::Lineitem invoice_lineitems
610 #
611 # module Invoice; class Lineitem < ActiveRecord::Base; end; end;
612 # file class table_name
613 # invoice/lineitem.rb Invoice::Lineitem lineitems
db045db @dhh Initial
dhh authored
614 #
98dc582 @lifo Merge docrails.
lifo authored
615 # Additionally, the class-level +table_name_prefix+ is prepended and the
616 # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of th...
jeremy authored
617 # the table name guess for an Invoice class becomes "myapp_invoices".
618 # Invoice::Lineitem becomes "myapp_invoice_lineitems".
619 #
620 # You can also overwrite this class method to allow for unguessable
621 # links, such as a Mouse class with a link to a "mice" table. Example:
db045db @dhh Initial
dhh authored
622 #
623 # class Mouse < ActiveRecord::Base
14101c7 @jeremy Nested classes are given table names prefixed by the singular form of th...
jeremy authored
624 # set_table_name "mice"
db045db @dhh Initial
dhh authored
625 # end
dcc4868 @dhh Fixed that Base.table_name would expect a parameter when used in has_and...
dhh authored
626 def table_name
d736568 Speed up the setting of table_name. Closes #2428.
Marcel Molina authored
627 reset_table_name
628 end
629
8d82bef @tchandy Documentation for #quoted_table_name method
tchandy authored
630 # Returns a quoted version of the table name, used to construct SQL statements.
798d282 @lifo Cache quoted_table_name
lifo authored
631 def quoted_table_name
632 @quoted_table_name ||= connection.quote_table_name(table_name)
633 end
634
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
635 # Computes the table name, (re)sets it internally, and returns it.
fed7d33 @dhh Fixed documentation
dhh authored
636 def reset_table_name #:nodoc:
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
637 self.table_name = compute_table_name
db045db @dhh Initial
dhh authored
638 end
639
5f7bc47 @wycats Rename modularized_table_name_prefix to full_table_name_prefix [#4032 st...
wycats authored
640 def full_table_name_prefix #:nodoc:
67d1cec @pixeltrix Add the ability to specify table_name_prefix on individual modules
pixeltrix authored
641 (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
642 end
643
9d2da04 @jeremy Cache inheritance_column. Closes #6592.
jeremy authored
644 # Defines the column name for use with single table inheritance
645 # -- can be set in subclasses like so: self.inheritance_column = "type_id"
db045db @dhh Initial
dhh authored
646 def inheritance_column
9d2da04 @jeremy Cache inheritance_column. Closes #6592.
jeremy authored
647 @inheritance_column ||= "type".freeze
db045db @dhh Initial
dhh authored
648 end
649
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored
650 # Lazy-set the sequence name to the connection's default. This method
651 # is only ever called once since set_sequence_name overrides it.
fed7d33 @dhh Fixed documentation
dhh authored
652 def sequence_name #:nodoc:
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored
653 reset_sequence_name
654 end
655
fed7d33 @dhh Fixed documentation
dhh authored
656 def reset_sequence_name #:nodoc:
7c8f3ed @jeremy r4325@asus: jeremy | 2005-11-12 03:57:46 -0800
jeremy authored
657 default = connection.default_sequence_name(table_name, primary_key)
658 set_sequence_name(default)
659 default
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to idiom...
dhh authored
660 end
661
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
662 # Sets the table name to use to the given value, or (if the value
4eab375 @dhh Finished polishing API docs
dhh authored
663 # is nil or false) to the value returned by the given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
664 #
665 # class Project < ActiveRecord::Base
666 # set_table_name "project"
667 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
668 def set_table_name(value = nil, &block)
47c9a35 @spastorino Reset quoted_table_name after set_table_name [#4568 state:resolved]
spastorino authored
669 @quoted_table_name = nil
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
670 define_attr_method :table_name, value, &block
671 end
672 alias :table_name= :set_table_name
673
674 # Sets the name of the inheritance column to use to the given value,
675 # or (if the value # is nil or false) to the value returned by the
4eab375 @dhh Finished polishing API docs
dhh authored
676 # given block.
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
677 #
678 # class Project < ActiveRecord::Base
679 # set_inheritance_column do
680 # original_inheritance_column + "_id"
681 # end
682 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
683 def set_inheritance_column(value = nil, &block)
1aa82b3 @dhh Added keyword-style approach to defining the custom relational bindings ...
dhh authored
684 define_attr_method :inheritance_column, value, &block
685 end
686 alias :inheritance_column= :set_inheritance_column
687
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to idiom...
dhh authored
688 # Sets the name of the sequence to use when generating ids to the given
689 # value, or (if the value is nil or false) to the value returned by the
7117fdb @jeremy r3616@asus: jeremy | 2005-09-26 23:09:28 -0700
jeremy authored
690 # given block. This is required for Oracle and is useful for any
691 # database which relies on sequences for primary key generation.
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to idiom...
dhh authored
692 #
2076dca @jeremy r3095@asus: jeremy | 2005-11-15 22:40:51 -0800
jeremy authored
693 # If a sequence name is not explicitly set when using Oracle or Firebird,
694 # it will default to the commonly used pattern of: #{table_name}_seq
695 #
696 # If a sequence name is not explicitly set when using PostgreSQL, it
697 # will discover the sequence corresponding to your primary key for you.
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to idiom...
dhh authored
698 #
699 # class Project < ActiveRecord::Base
700 # set_sequence_name "projectseq" # default would have been "project_seq"
701 # end
c9c1852 @dhh Making ActiveRecord faster [skaes]
dhh authored
702 def set_sequence_name(value = nil, &block)
14ea312 @dhh Made Oracle a first-class connection adapter by adhering closer to idiom...
dhh authored
703 define_attr_method :sequence_name, value, &block
704 end
705 alias :sequence_name= :set_sequence_name
706
db045db @dhh Initial
dhh authored
707 # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
708 def class_name(table_name = table_name) # :nodoc:
709 # remove any prefix and/or suffix from the table name
81737fc @jeremy r1613@asus: jeremy | 2005-07-03 07:04:53 -0700
jeremy authored
710 class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize
711 class_name = class_name.singularize if pluralize_table_names
712 class_name
db045db @dhh Initial
dhh authored
713 end
714
816f37a @dhh Added migration support to SQL Server adapter (please someone do the sam...
dhh authored
715 # Indicates whether the table associated with this class exists
716 def table_exists?
8877ab5 @tarmo Added AbstractAdapter#table_exists? and made AbstractAdapter#table imple...
tarmo authored
717 connection.table_exists?(table_name)
816f37a @dhh Added migration support to SQL Server adapter (please someone do the sam...
dhh authored
718 end
719
db045db @dhh Initial
dhh authored
720 # Returns an array of column objects for the table associated with this class.
721 def columns
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized inst...
jeremy authored
722 unless defined?(@columns) && @columns
c0899bc Add convenience predicate methods on Column class. In partial fullfilmen...
Marcel Molina authored
723 @columns = connection.columns(table_name, "#{name} Columns")
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized inst...
jeremy authored
724 @columns.each { |column| column.primary = column.name == primary_key }
c0899bc Add convenience predicate methods on Column class. In partial fullfilmen...
Marcel Molina authored
725 end
726 @columns
db045db @dhh Initial
dhh authored
727 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
728
3b4450b @NZKoz Docs fix for columns_hash [bradediger]
NZKoz authored
729 # Returns a hash of column objects for the table associated with this class.
db045db @dhh Initial
dhh authored
730 def columns_hash
731 @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
732 end
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlguy@...
jeremy authored
733
fed7d33 @dhh Fixed documentation
dhh authored
734 # Returns an array of column names as strings.
49d0f0c @dhh Speeded up eager loading a whole bunch
dhh authored
735 def column_names
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlguy@...
jeremy authored
736 @column_names ||= columns.map { |column| column.name }
49d0f0c @dhh Speeded up eager loading a whole bunch
dhh authored
737 end
db045db @dhh Initial
dhh authored
738
2948910 Misc doc fixes (typos/grammar/etc.). Closes #2430.
Marcel Molina authored
739 # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
740 # and columns used for single table inheritance have been removed.
db045db @dhh Initial
dhh authored
741 def content_columns
c0899bc Add convenience predicate methods on Column class. In partial fullfilmen...
Marcel Molina authored
742 @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
db045db @dhh Initial
dhh authored
743 end
744
745 # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
746 # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
747 # is available.
fed7d33 @dhh Fixed documentation
dhh authored
748 def column_methods_hash #:nodoc:
d0bd3b5 @jeremy Return PostgreSQL columns in the order they are declared #1374 (perlguy@...
jeremy authored
749 @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
3ab3a70 @jeremy Clarify semantics of ActiveRecord::Base#respond_to? Closes #2560.
jeremy authored
750 attr_name = attr.to_s
751 methods[attr.to_sym] = attr_name
752 methods["#{attr}=".to_sym] = attr_name
753 methods["#{attr}?".to_sym] = attr_name
754 methods["#{attr}_before_type_cast".to_sym] = attr_name
db045db @dhh Initial
dhh authored
755 methods
756 end
757 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
758
a293278 @lifo Merge docrails
lifo authored
759 # Resets all the cached information about columns, which will cause them
760 # to be reloaded on the next request.
761 #
762 # The most common usage pattern for this method is probably in a migration,
763 # when just after creating a table you want to populate it with some default
764 # values, eg:
765 #
766 # class CreateJobLevels < ActiveRecord::Migration
767 # def self.up
768 # create_table :job_levels do |t|
769 # t.integer :id
770 # t.string :name
771 #
772 # t.timestamps
773 # end
774 #
775 # JobLevel.reset_column_information
776 # %w{assistant executive manager director}.each do |type|
777 # JobLevel.create(:name => type)
778 # end
779 # end
780 #
781 # def self.down
782 # drop_table :job_levels
783 # end
784 # end
1314f48 @dhh Added methods for resetting the cached information on classes that you w...
dhh authored
785 def reset_column_information
e129c56 @josh Wrap up attribute method reset concerns in 'undefine_attribute_methods'
josh authored
786 undefine_attribute_methods
d2c4b3b @lifo Rename Model.engine to active_relation_engine. Cache arel_table and the ...
lifo authored
787 @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
6e3bee6 @lifo Cache Model.arel_table
lifo authored
788 @arel_engine = @unscoped = @arel_table = nil
1314f48 @dhh Added methods for resetting the cached information on classes that you w...
dhh authored
789 end
790
4eab375 @dhh Finished polishing API docs
dhh authored
791 def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
033e0a0 @josevalim ActiveRecord and ActionPack now use the new descendants implementation.
josevalim authored
792 descendants.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
1314f48 @dhh Added methods for resetting the cached information on classes that you w...
dhh authored
793 end
db045db @dhh Initial
dhh authored
794
ce48b31 @spastorino Makes validates_acceptance_of to not override database fields [#4460 sta...
spastorino authored
795 def attribute_method?(attribute)
209ab7e @josevalim Fix failing test.
josevalim authored
796 super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
ce48b31 @spastorino Makes validates_acceptance_of to not override database fields [#4460 sta...
spastorino authored
797 end
798
e714b49 @josevalim Move validator, human_name and human_attribute_name to ActiveModel, remo...
josevalim authored
799 # Set the lookup ancestors for ActiveModel.
800 def lookup_ancestors #:nodoc:
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored
801 klass = self
802 classes = [klass]
0905396 @miloops construct_finder_sql now use Arel
miloops authored
803 while klass != klass.base_class
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored
804 classes << klass = klass.superclass
805 end
806 classes
807 rescue
808 # OPTIMIZE this rescue is to fix this test: ./test/cases/reflection_test.rb:56:in `test_human_name_for_column'
e033b5d @lifo Merge docrails
lifo authored
809 # Apparently the method base_class causes some trouble.
ffeab4e Cleaned up ActiveRecord i18n scoping
Iain Hecker authored
810 # It now works for sure.
811 [self]
812 end
813
e714b49 @josevalim Move validator, human_name and human_attribute_name to ActiveModel, remo...
josevalim authored
814 # Set the i18n scope to overwrite ActiveModel.
815 def i18n_scope #:nodoc:
816 :activerecord
db045db @dhh Initial
dhh authored
817 end
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
818
06afb8c @jeremy Subclasses of an abstract class work with single-table inheritance. Refe...
jeremy authored
819 # True if this isn't a concrete subclass needing a STI type condition.
820 def descends_from_active_record?
821 if superclass.abstract_class?
822 superclass.descends_from_active_record?
823 else
824 superclass == Base || !columns_hash.include?(inheritance_column)
825 end
db045db @dhh Initial
dhh authored
826 end
827
b4ec990 @NZKoz Cache the descends_from_activerecord? call to speed up query generation....
NZKoz authored
828 def finder_needs_type_condition? #:nodoc:
829 # This is like this because benchmarking justifies the strange :false stuff
830 :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
831 end
832
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo .....
jeremy authored
833 # Returns a string like 'Post id:integer, title:string, body:text'
52a9e50 @dhh Added ActiveRecord::Base.inspect to return a column-view like #<Post id:...
dhh authored
834 def inspect
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo .....
jeremy authored
835 if self == Base
836 super
837 elsif abstract_class?
838 "#{super}(abstract)"
bb94ce9 @NZKoz Let inspect on AR classes work when the table doesn't exist. Closes #919...
NZKoz authored
839 elsif table_exists?
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo .....
jeremy authored
840 attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
841 "#{super}(#{attr_list})"
bb94ce9 @NZKoz Let inspect on AR classes work when the table doesn't exist. Closes #919...
NZKoz authored
842 else
843 "#{super}(Table doesn't exist)"
d0360a4 @jeremy Base.inspect handles Base itself and abstract_class? Don't use #<Foo .....
jeremy authored
844 end
52a9e50 @dhh Added ActiveRecord::Base.inspect to return a column-view like #<Post id:...
dhh authored
845 end
846
b445ab9 @NZKoz Rename quote to quote_value so the name can be used in AR models. #3628 ...
NZKoz authored
847 def quote_value(value, column = nil) #:nodoc:
b2c0ddf Add support for FrontBase (http://www.frontbase.com/) with a new adapter...
Marcel Molina authored
848 connection.quote(value,column)
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
849 end
850
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
851 # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
4eab375 @dhh Finished polishing API docs
dhh authored
852 def sanitize(object) #:nodoc:
4940383 @dhh Fixed value quoting in all generated SQL statements, so that integers ar...
dhh authored
853 connection.quote(object)
db045db @dhh Initial
dhh authored
854 end
855
97849de @dhh Fixed that association proxies would fail === tests like PremiumSubscrip...
dhh authored
856 # Overwrite the default class equality method to provide support for association proxies.
857 def ===(object)
858 object.is_a?(self)
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
859 end
b840e4e Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveReco...
Marcel Molina authored
860
d2f4750 @jamis Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jam...
jamis authored
861 # Returns the base AR subclass that this class descends from. If A
862 # extends AR::Base, A.base_class will return A. If B descends from A
863 # through some arbitrarily deep hierarchy, B.base_class will return A.
864 def base_class
865 class_of_active_record_descendant(self)
866 end
867
98dc582 @lifo Merge docrails.
lifo authored
868 # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of the ...
technoweenie authored
869 attr_accessor :abstract_class
870
871 # Returns whether this class is a base AR class. If A is a base class and
872 # B descends from A, then B.base_class will return B.
873 def abstract_class?
8b5f4e4 @jeremy Ruby 1.9 compat: fix warnings, shadowed block vars, and unitialized inst...
jeremy authored
874 defined?(@abstract_class) && @abstract_class == true
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of the ...
technoweenie authored
875 end
876
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #11538....
lifo authored
877 def respond_to?(method_id, include_private = false)
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
878 if match = DynamicFinderMatch.match(method_id)
879 return true if all_attributes_exists?(match.attribute_names)
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class methods...
yaroslav authored
880 elsif match = DynamicScopeMatch.match(method_id)
881 return true if all_attributes_exists?(match.attribute_names)
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #11538....
lifo authored
882 end
c3aa2bc @Manfred Ensure nested with_scope merges conditions inside out [#2193 state:resol...
Manfred authored
883
4f39382 @lifo Ensure that respond_to? considers dynamic finder methods. Closes #11538....
lifo authored
884 super
885 end
886
72483c0 @technoweenie Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_ful...
technoweenie authored
887 def sti_name
888 store_full_sti_class ? name : name.demodulize
889 end
890
cd90dcb @lifo Rename Model.active_relation to Model.unscoped
lifo authored
891 def unscoped
892 @unscoped ||= Relation.new(self, arel_table)
893 finder_needs_type_condition? ? @unscoped.where(type_condition) : @unscoped
f4a2356 @miloops Added ActiveRecord::Base#(where|join|project|group|order|take|skip) meth...
miloops authored
894 end
895
6e3bee6 @lifo Cache Model.arel_table
lifo authored
896 def arel_table
897 @arel_table ||= Arel::Table.new(table_name, :engine => arel_engine)
d2c4b3b @lifo Rename Model.engine to active_relation_engine. Cache arel_table and the ...
lifo authored
898 end
899
5a52523 @lifo Rename active_relation_engine -> arel_engine and active_relation_table -...
lifo authored
900 def arel_engine
901 @arel_engine ||= begin
a115b5d @lifo Ensure using proper engine for Arel::Table
lifo authored
902 if self == ActiveRecord::Base
903 Arel::Table.engine
904 else
5a52523 @lifo Rename active_relation_engine -> arel_engine and active_relation_table -...
lifo authored
905 connection_handler.connection_pools[name] ? Arel::Sql::Engine.new(self) : superclass.arel_engine
a115b5d @lifo Ensure using proper engine for Arel::Table
lifo authored
906 end
907 end
77c23b2 @lifo Use PredicateBuilder for sql hash sanitization
lifo authored
908 end
909
db045db @dhh Initial
dhh authored
910 private
4b4dd54 @jeremy Clashing type columns due to a sloppy join shouldn't wreck single-table ...
jeremy authored
911 # Finder methods must instantiate through this method to work with the
912 # single-table inheritance model that makes it possible to create
913 # objects of different types from the same table.
db045db @dhh Initial
dhh authored
914 def instantiate(record)
3fc2d1e @jeremy Extract class-finder method from instantiate
jeremy authored
915 object = find_sti_class(record[inheritance_column]).allocate
605bc77 @dhh Added a better exception for when a type column is used in a table witho...
dhh authored
916
6d30002 @lifo Revert "Refactoring attributes/types" [#3348 state:open]
lifo authored
917 object.instance_variable_set(:'@attributes', record)
3fc2d1e @jeremy Extract class-finder method from instantiate
jeremy authored
918 object.instance_variable_set(:'@attributes_cache', {})
115230e @tenderlove cleaning up some test warnings
tenderlove authored
919 object.instance_variable_set(:@new_record, false)
5de3698 @tenderlove cleaning up many more warnings in activerecord [#4180 state:resolved]
tenderlove authored
920 object.instance_variable_set(:@readonly, false)
921 object.instance_variable_set(:@destroyed, false)
922 object.instance_variable_set(:@marked_for_destruction, false)
8c3e46c @tenderlove clean up more warnings, remove unnecessary methods, fix eval line number...
tenderlove authored
923 object.instance_variable_set(:@previously_changed, {})
924 object.instance_variable_set(:@changed_attributes, {})
55efae2 @jeremy Performance: absorb instantiate and initialize_with_callbacks into the B...
jeremy authored
925
4f37b97 @josevalim Changed ActiveRecord to use new callbacks and speed up observers by only...
josevalim authored
926 object.send(:_run_find_callbacks)
927 object.send(:_run_initialize_callbacks)
55efae2 @jeremy Performance: absorb instantiate and initialize_with_callbacks into the B...
jeremy authored
928
81737fc @jeremy r1613@asus: jeremy | 2005-07-03 07:04:53 -0700
jeremy authored
929 object
db045db @dhh Initial
dhh authored
930 end
81737fc @jeremy r1613@asus: jeremy | 2005-07-03 07:04:53 -0700
jeremy authored
931
3fc2d1e @jeremy Extract class-finder method from instantiate
jeremy authored
932 def find_sti_class(type_name)
933 if type_name.blank? || !columns_hash.include?(inheritance_column)
934 self
935 else
936 begin
937 compute_type(type_name)
938 rescue NameError
939 raise SubclassNotFound,
940 "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
941 "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
942 "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
943 "or overwrite #{name}.inheritance_column to use another column for that information."
944 end
945 end
946 end
947
bed9179 @lifo Make scopes use relations under the hood
lifo authored
948 def construct_finder_arel(options = {}, scope = nil)
8ff2fb6 @lifo Make default_scope work with Relations
lifo authored
949 relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : unscoped.merge(options)
bed9179 @lifo Make scopes use relations under the hood
lifo authored
950 relation = scope.merge(relation) if scope
6b67df7 @miloops Revert "Revert "Add readonly support for relations.""
miloops authored
951 relation
19d2ff8 @miloops Calculations now use Arel to construct the query.
miloops authored
952 end
953
2d0bc08 @lifo Make type_condition return Arel predicate and not a string condition
lifo authored
954 def type_condition
5a52523 @lifo Rename active_relation_engine -> arel_engine and active_relation_table -...
lifo authored
955 sti_column = arel_table[inheritance_column]
d200d08 @lifo Use arel for building the STI type condition
lifo authored
956 condition = sti_column.eq(sti_name)
033e0a0 @josevalim ActiveRecord and ActionPack now use the new descendants implementation.
josevalim authored
957 descendants.each { |subclass| condition = condition.or(sti_column.eq(subclass.sti_name)) }
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
958
2d0bc08 @lifo Make type_condition return Arel predicate and not a string condition
lifo authored
959 condition
db045db @dhh Initial
dhh authored
960 end
961
962 # Guesses the table name, but does not decorate it with prefix and suffix information.
def7460 @technoweenie Added Base.abstract_class? that marks which classes are not part of the ...
technoweenie authored
963 def undecorated_table_name(class_name = base_class.name)
3b0e1d9 @josh Prefer string core_ext inflector methods over directly accessing Inflect...
josh authored
964 table_name = class_name.to_s.demodulize.underscore
965 table_name = table_name.pluralize if pluralize_table_names
6e39c9e @jeremy r1614@asus: jeremy | 2005-07-03 08:01:08 -0700
jeremy authored
966 table_name
db045db @dhh Initial
dhh authored
967 end
968
4a8c880 @fxn refactors AR::Base#reset_table_name
fxn authored
969 # Computes and returns a table name according to default conventions.
970 def compute_table_name
971 base = base_class
972 if self == base
973 # Nested classes are prefixed with singular parent table name.
974 if parent < ActiveRecord::Base && !parent.abstract_class?
975 contained = parent.table_name
976 contained = contained.singularize if parent.pluralize_table_names
977 contained << '_'
978 end
979 "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
980 else
981 # STI subclasses always use their superclass' table.
982 base.table_name
983 end
984 end
985
39e1ac6 @lifo Merge docrails
lifo authored
986 # Enables dynamic finders like <tt>find_by_user_name(user_name)</tt> and <tt>find_by_user_name_and_password(user_name, password)</tt>
1efc8ed @lifo Fix dynamic finder docs
lifo authored
987 # that are turned into <tt>where(:user_name => user_name).first</tt> and <tt>where(:user_name => user_name, :password => :password).first</tt>
988 # respectively. Also works for <tt>all</tt> by using <tt>find_all_by_amount(50)</tt> that is turned into <tt>where(:amount => 50).all</tt>.
2a30594 @technoweenie documentation project patches, closes #7342, #7319, #7316, #7190 [jeremy...
technoweenie authored
989 #
39e1ac6 @lifo Merge docrails
lifo authored
990 # It's even possible to use all the additional parameters to +find+. For example, the full interface for +find_all_by_amount+
991 # is actually <tt>find_all_by_amount(amount, options)</tt>.
4a1388a Define dynamic finders as real methods after first usage. Close #9317
Tobias Lütke authored
992 #
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class methods...
yaroslav authored
993 # Each dynamic finder, scope or initializer/creator is also defined in the class after it is first invoked, so that future
4a1388a Define dynamic finders as real methods after first usage. Close #9317
Tobias Lütke authored
994 # attempts to use it do not run through method_missing.
8a77c4a Fixed issue where block is not called on the very first invocation of a ...
Ken Miller authored
995 def method_missing(method_id, *arguments, &block)
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
996 if match = DynamicFinderMatch.match(method_id)
997 attribute_names = match.attribute_names
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
998 super unless all_attributes_exists?(attribute_names)
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
999 if match.finder?
8829d6e @lifo Make Model.find_by_* and Model.find_all_by_* use relations and remove dy...
lifo authored
1000 options = arguments.extract_options!
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1001 relation = options.any? ? construct_finder_arel(options, current_scoped_methods) : scoped
8829d6e @lifo Make Model.find_by_* and Model.find_all_by_* use relations and remove dy...
lifo authored
1002 relation.send :find_by_attributes, match, attribute_names, *arguments
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
1003 elsif match.instantiator?
85770ec @lifo Make Model.find_or_create_by_* and find_or_initialize_by_* use relations...
lifo authored
1004 scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block
143f5fb @joshsusser refactor dynamic finder name matching into its own class
joshsusser authored
1005 end
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class methods...
yaroslav authored
1006 elsif match = DynamicScopeMatch.match(method_id)
1007 attribute_names = match.attribute_names
1008 super unless all_attributes_exists?(attribute_names)
1009 if match.scope?
13e00ce @spastorino fix stack trace lines on class_eval
spastorino authored
1010 self.class_eval <<-METHOD, __FILE__, __LINE__ + 1
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class methods...
yaroslav authored
1011 def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)
1012 options = args.extract_options! # options = args.extract_options!
1013 attributes = construct_attributes_from_arguments( # attributes = construct_attributes_from_arguments(
1014 [:#{attribute_names.join(',:')}], args # [:user_name, :password], args
1015 ) # )
0905396 @miloops construct_finder_sql now use Arel
miloops authored
1016 #
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class methods...
yaroslav authored
1017 scoped(:conditions => attributes) # scoped(:conditions => attributes)
1018 end # end
13e00ce @spastorino fix stack trace lines on class_eval
spastorino authored
1019 METHOD
66ee589 @yaroslav Introduce dynamic scopes for ActiveRecord: you can now use class methods...
yaroslav authored
1020 send(method_id, *arguments)
1021 end
ac8fd7d @dhh Added dynamic attribute-based finders as a cleaner way of getting object...
dhh authored
1022 else
1023 super
1024 end
1025 end
db045db @dhh Initial
dhh authored
1026
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
1027 def construct_attributes_from_arguments(attribute_names, arguments)
1028 attributes = {}
1029 attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
1030 attributes
1031 end
1032
abdf546 @jeremy Support aggregations in finder conditions. Closes #10572.
jeremy authored
1033 # Similar in purpose to +expand_hash_conditions_for_aggregates+.
1034 def expand_attribute_names_for_aggregates(attribute_names)
1035 expanded_attribute_names = []
1036 attribute_names.each do |attribute_name|
1037 unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
1038 aggregate_mapping(aggregation).each do |field_attr, aggregate_attr|
1039 expanded_attribute_names << field_attr
1040 end
1041 else
1042 expanded_attribute_names << attribute_name
1043 end
1044 end
1045 expanded_attribute_names
1046 end
1047
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
1048 def all_attributes_exists?(attribute_names)
abdf546 @jeremy Support aggregations in finder conditions. Closes #10572.
jeremy authored
1049 attribute_names = expand_attribute_names_for_aggregates(attribute_names)
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
1050 attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) }
7367325 @jeremy Document Active Record exceptions. Closes #10444.
jeremy authored
1051 end
a5a82d9 @dhh Added extension capabilities to has_many and has_and_belongs_to_many pro...
dhh authored
1052
db045db @dhh Initial
dhh authored
1053 protected
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1054 # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1055 # method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while
1056 # <tt>:create</tt> parameters are an attributes hash.
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1057 #
1058 # class Article < ActiveRecord::Base
1059 # def self.create_with_scope
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1060 # with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1061 # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
1062 # a = create(1)
1063 # a.blog_id # => 1
1064 # end
1065 # end
1066 # end
1067 #
b0391d1 @dhh Docfix (closes #8674)
dhh authored
1068 # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1069 # <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged.
39e1ac6 @lifo Merge docrails
lifo authored
1070 #
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1071 # <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing
39e1ac6 @lifo Merge docrails
lifo authored
1072 # problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the
1073 # array of strings format for your joins.
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1074 #
1075 # class Article < ActiveRecord::Base
1076 # def self.find_with_scope
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1077 # with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do
1078 # with_scope(:find => limit(10)) do
1079 # all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1080 # end
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1081 # with_scope(:find => where(:author_id => 3)) do
1082 # all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1083 # end
1084 # end
1085 # end
1086 # end
1087 #
7143d80 Smattering of grammatical fixes to documentation. Closes #10083 [BobSilv...
Marcel Molina authored
1088 # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method.
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1089 #
1090 # class Article < ActiveRecord::Base
1091 # def self.find_with_exclusive_scope
2c27e3d @lifo Some doc updates reflecting the new query API
lifo authored
1092 # with_scope(:find => where(:blog_id => 1).limit(1)) do
1093 # with_exclusive_scope(:find => limit(10))
1094 # all # => SELECT * from articles LIMIT 10
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1095 # end
1096 # end
1097 # end
1098 # end
a293278 @lifo Merge docrails
lifo authored
1099 #
1100 # *Note*: the +:find+ scope also has effect on update and deletion methods,
1101 # like +update_all+ and +delete_all+.
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1102 def with_scope(method_scoping = {}, action = :merge, &block)
1103 method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)
1104
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1105 if method_scoping.is_a?(Hash)
1106 # Dup first and second level of hash (method and params).
1107 method_scoping = method_scoping.inject({}) do |hash, (method, params)|
1108 hash[method] = (params == true) ? params : params.dup
1109 hash
1110 end
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1111
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1112 method_scoping.assert_valid_keys([ :find, :create ])
1113 relation = construct_finder_arel(method_scoping[:find] || {})
1114
1115 if current_scoped_methods && current_scoped_methods.create_with_value && method_scoping[:create]
1b78a3f @lifo with_scope no longer needs :reverse_merge
lifo authored
1116 scope_for_create = if action == :merge
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1117 current_scoped_methods.create_with_value.merge(method_scoping[:create])
1118 else
1119 method_scoping[:create]
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1120 end
bed9179 @lifo Make scopes use relations under the hood
lifo authored
1121
1122 relation = relation.create_with(scope_for_create)
1123 else
1124 scope_for_create = method_scoping[:create]
1125 scope_for_create ||= current_scoped_methods.create_with_value if current_scoped_methods
1126 relation = relation.create_with(scope_for_create) if scope_for_create
1127 end
1128
1129 method_scoping = relation
1130 end
1131
1b78a3f @lifo with_scope no longer needs :reverse_merge
lifo authored
1132 method_scoping = current_scoped_methods.merge(method_scoping) if current_scoped_methods && action == :merge
1edd21b @jeremy with_scope is protected. Closes #8524.
jeremy authored
1133
1134 self.scoped_methods << method_scoping
1135 begin
1136 yield
1137 ensure
1138 self.scoped_methods.pop
1139 end
1140 end
1141
1142 # Works like with_scope, but discards any nested properties.
1143 def with_exclusive_scope(method_scoping = {}, &block)
1144 with_scope(method_scoping, :overwrite, &block)
1145 end
1146
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
1147 # Sets the default options for the model. The format of the
c4023cb @mernen Update documentation for default_scope
mernen authored
1148 # <tt>options</tt> argument is the same as in find.
2530d0e @lifo Added default_scope to Base [#1381 state:committed] (Paweł Kondzior)
lifo authored
1149 #
1150 # class Person < ActiveRecord::Base
a4eab8f @dhh Update example of default_scope to use the new arel finder syntax
dhh authored
1151 # default_scope order('last_name, first_name')
2530d0e @lifo