Recent notes
RSS feedRescuing DeleteRestrictionError via flash message
Model
class ShareType < ActiveRecord::Base has_many :shares, :dependent => :restrict end
Controller
class ShareTypesController < ApplicationController def destroy begin @share_type.destroy flash[:success] = "successfully destroyed." rescue ActiveRecord::DeleteRestrictionError => e @share_type.errors.add(:base, e) flash[:error] = "#{e}" ensure redirect_to share_types_url end end end
now they are built-in
in ruby 1.9 and afterwards, the to_enum and enum_for(synonym for to_enum) methods are buil-in to the language. so there’s no need to require that any more.
default value for :use_full_path
FYI, It in Rails 2.1.1 the default value for :use_full_path has changed from true to false.
This will show up as an error stating “No such file or directory”
Basic usage
Basic usage example:
class User < ActiveRecord::Base #... skip_callback :create, :after, :send_welcome_email #... end
sure, but what types are there to chose from?
the ‘symbol’ parameter is not something specific like ‘:after_save’, but rather ‘:save’
I suppose ‘:update’ works as well.
includes request parameters
fullpath includes request parameters in the result
Multiple update, on query ?
Person.update(people.keys, people.values)
Will this request issue one or multiple queries to update the table data (as in http://stackoverflow.com/questions/3432/multiple-updates-in-mysql#3466 )
The answer is: it will do TWO queries per updated row. One select and one update.
Dup vs Clone difference
As for me main difference between .dup and .clone , that first one doesn’t not freeze result object if initial object was frozen.
No way to use custom message
In what appears to be a bug, there appears to be no way to use a custom error message when using this validator.
Available Options and their meaning
key
Name of the cookie for the session
secure
If true, session cookie is sent only to https hosts. This protects your app from session hijacking ( remember firesheep? )
expire_after
Self explanatory (e.g. 60.minutes)
domain
To which domain the cookie declares to be for
This very good post shows how to use :domain and :key to implement single-sign-on: http://itshouldbeuseful.wordpress.com/2011/02/02/rails-authlogic-and-single-sign-on/
Common Validator options
Most validators will support all of the following common options: (Through ActiveModel::Errors::CALLBACK_OPTIONS (http://apidock.com/rails/ActiveModel/Errors))
-
:if
-
:unless
-
:allow_blank
-
:allow_nil
Another way to use
<%=
link_to_unless_current("Profile", profile_path)
%> also works (instead of pointing to controller/action)
Default values
For common attributes in several models, you can set a default human name like this:
de.yml
de: attributes: bez: Bezeichnung abk: Abkürzung
Updating nested attributes of one-to-one associations
As the documentation implicitly mentions, when updating nested attributes of a one-to-one relationship, you need to pass the ID of the nested attribute itself, otherwise a new record will be created.
This works fine:
params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
However, the following line will build and save a new record, which is usually not what you want for one-to-one:
params = { :member => { :avatar_attributes => { :icon => 'sad' } } }
Alternatively, you can use the ‘update_only’ option. This option will ensure that an existing record will always be updated, even if the ID is not specified:
accepts_nested_attributes_for :avatar, :update_only => true
available column types
Rails 3.0.9 update for RobinWu’s post
Available column types:
:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean
Example:
MyClass < ActiveRecord::Migration
def change create_table :myclass do |t| t.string :name t.text :content end
end
Uses same arguments as Time#strftime
I believe this uses the same parsing format as strftime.
Typo in example above
You aren’t mistaken. That is an error in the example with the block above. There’s an extra ‘(’ character.
RailsCast about Responders
See Ryan Bate’s excellent RailsCast #224 about Responders in Rails 3.x: http://asciicasts.com/episodes/224-controllers-in-rails-3
RE: Don't Use to_formatted_s(:db) on an Array of IDs
The reason it doesnt work @joshuapinter for IDs is because if you look at the source:
case format when :db if respond_to?(:empty?) && self.empty? "null" else collect { |element| element.id }.join(",") # look at this line end else to_default_s end
It maps/collects the object ids and then joins them using a comma ; so in the case of 60 for instance :
60.object_id #=> 121
60.id #=> 121
:url conflicts with :format
If you are passing both :url and :format, url overwrites the use of format, so you’ll need to pass it in the url like so:
form_for user, :url => user_path(@user, :format => :json)
Loop through matches of your regular expression-based search
If you want to loop through the matches of a regular expression, String#scan is your friend. You can do something like this:
matches = '12345'.scan(/\d/) matches.each do |m| puts m end # => 1 # => 2 # => 3 # => 4 # => 5
Typecasting return values
A better way to typecast the result array is to use AR’s typecasting capabilities. Example:
column = Company.columns_hash['id'] select_values("SELECT id FROM companies LIMIT 3").map do |value| column.type_cast(value) end
don't forget :root
You can rename the root tag if you don’t like what is being generated.
line_item.to_xml(:skip_instruct => true, :root => 'line-item')
require it
require ‘action_dispatch/testing/test_process’
select_values returns Strings for postgreSQL
Will return strings too when using postgreSQL and gem pg (0.11.0).
bug's fixed, though
in 3.1.0. it works in sqlite3 even, via nested query
but 3.0.3, 3.0.7-9 all broken
validating a database column acceptance
accept option should be set to true if you are validating a database column, since the attribute is typecast from “1” to true before validation
validates :terms, acceptance: { allow_nil: false, accept: true }
Unusual block calling
It is important to note that the block form of this method is unlike any other block form in Rails. You would expect this to work:
<%= f.label :terms_and_conditions do %> Accept <%= link_to_page 'Terms and Conditions' %> <% end %>
But doing this ends up messing up the form (I ended up with the form repeating itself). Instead you need to do:
<%= f.label :terms_and_conditions do 'Accept ' + link_to_page('Terms and Conditions') end %>
Which is really only mildly better than not using the block form:
<%= f.label :terms_and_conditions, 'Accept ' + link_to_page('Terms and Conditions') %>
You are actually better of using capture if your code lends itself to the first non-working form:
<%= f.label :terms_and_conditions, (capture do %> Accept <%= link_to_page 'Terms and Conditions' %> <% end) %>
Or if you prefer brackets to parenthesis you can do:
<%= f.label :terms_and_conditions, capture { %> Accept <%= link_to_page 'Terms and Conditions' %> <% } %>