Skip to content

HTTPS clone URL

Subversion checkout URL

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