Recent good notes
RSS feedWorks with URLs too!
You can use it for web urls as well:
path, file = File.split('/uploads/art/2869-speaking-of-pic.jpg') p path # => "/uploads/art" p file # => "2869-speaking-of-pic.jpg"
And you can also use join, to merge url back from the components:
path = File.join(["/uploads/art", "2869-speaking-of-pic.jpg"]) p path # => "/uploads/art/2869-speaking-of-pic.jpg"
Using #join and #split for operations on files and path parts of the URLs is generally better than simply joining/splitting strings by ‘/’ symbol. Mostly because of normalization:
File.split('//tmp///someimage.jpg') # => ["/tmp", "someimage.jpg"] '//tmp///someimage.jpg'.split('/') # => ["", "", "tmp", "", "", "someimage.jpg"]
Same thing happens with join.
Seriously! Do not forget the brackets
thank you source jamesandre.ws
the form_for([:admin, @user]) must have the [] brackets to avoid errors like “Only get requests are allowed”
<% form_for([:admin, @user]) do |f| %> <%= render :partial => 'form' %> <%= submit_tag "Create" %> <% end %>
More on deprecation
This is not deprecated. I think the docs are confused because the validate, validate_on_create, and validate_on_update methods are actually callbacks and not explicitly defined on their own. The correct usage is the same as in the docs above.
:prefix option
Be aware!
By default, if you do select_month(Date.today, :field_name => ‘start’) it will generate select tag with name “date[start]”. If you want it to be something other than date[], add :prefix option, like this:
select_month(Date.today, :field_name => 'start', :prefix => 'timer')
This will render select tag with name “timer[start]”.
Taken from sources of name_and_id_from_options method.
Link to caller URL
link_to “Back”, :back
Documentation for Associations
You are most likely looking for ActiveRecord::Associations::ClassMethods
If you're not using resource
If you don’t use resource for your remote_form_for, then :url option is necessary.
For example:
<% remote_form_for "not_resource" do |f| ... %>
won’t work. But with :url option, it will:
<% remote_form_for "not_resource", :url => { :controller => "recommend", :action => "send" } do ... %>
has_one Nesting in Rails 2.0
Routers:
map.resources :user, :has_one => [:avatar]
Views:
form_for [@user, @avatar], :url => user_avatar_url(@user) do |f| ... end
Example using simple_matcher
This is extracted from: http://blog.davidchelimsky.net/2008/6/7/thoughts-on-the-dance-off
Here’s an example:
def be_sorted simple_matcher("a sorted list") {|actual| actual.sort == actual} end [1,2,3].should be_sorted
The block is handed the actual value. If the block returns true, the expectation passes. If it returns false, it fails with the following message:
expected “a sorted list” but got [1, 3, 2]
If you say [1,2,3].should_not be_sorted you’d get this message instead=:
expected not to get “a sorted list”, but got [1, 2, 3]
As of now, you don’t get any control over the failure message other than the string you pass to the simple_matcher method
Pass the observed fields value as a parameter in the Ajax request
Use encodeURIComponent with with to pass an encoded value as a parameter (POST or GET) of the AJAX request. For example:
<%= observe_field :company_id,
:url => {:action => ‘facilities’, :only_path => false}, :with => “‘company=’ + encodeURIComponent(value)” %> Also, setting only_path => false for the URL ensures that the full URL (including host and protocol) is used for the AJAX request.
Example of composed_of composition class implementation
If we have following code in model:
composed_of :temperature, :mapping => %w(celsius)
Then our composition class can be this:
class Temperature def initialize(celsius) @celsius = celsius end # This method is called by ActiveRecord, when record is saved. # Result of this method will be stored in table in "celsius" field, # and later when the record is loaded again, this will go to # our Temperature#new constructor. def celsius @celsius end # This is example of method that we can add to make this composition useful. def farenheit @celsius * 9/5 + 32 end end
has_many :through
It’s is recommended to use has_many :through association instead of has_and_belongs_to_many. has_many :through is better supported and generally easier to work with once you grasp the idea.
Compare old and new form for
Old form for
<% form_for :user, :url => users_path do %> <%= render :partial => 'form' %> <%= submit_tag 'Create' %> <% end %>
New form for
<% form_for(@user) do |f| %> <%= render :partial => f %> <%= submit_tag 'Create' %> <% end %>
All methods
create_table :table do |t|
t.column # adds an ordinary column. Ex: t.column(:name, :string) t.index # adds a new index. t.timestamps t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80) t.change_default # changes the column default value. t.rename # changes the name of the column. t.references t.belongs_to t.string t.text t.integer t.float t.decimal t.datetime t.timestamp t.time t.date t.binary t.boolean t.remove t.remove_references t.remove_belongs_to t.remove_index t.remove_timestamps end
All methods
change_table :table do |t|
t.column # adds an ordinary column. Ex: t.column(:name, :string) t.index # adds a new index. t.timestamps t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80) t.change_default # changes the column default value. t.rename # changes the name of the column. t.references t.belongs_to t.string t.text t.integer t.float t.decimal t.datetime t.timestamp t.time t.date t.binary t.boolean t.remove t.remove_references t.remove_belongs_to t.remove_index t.remove_timestamps end
Method description from Rails 2.0
If text is longer than length, text will be truncated to the length of length (defaults to 30) and the last characters will be replaced with the truncate_string (defaults to “…”).
Examples
truncate("Once upon a time in a world far far away", 14) # => Once upon a... truncate("Once upon a time in a world far far away") # => Once upon a time in a world f... truncate("And they found that many people were sleeping better.", 25, "(clipped)") # => And they found that many (clipped) truncate("And they found that many people were sleeping better.", 15, "... (continued)") # => And they found... (continued)
:expires_in option
If you need :expires_in functionality in Rails 2.1, you can use this plugin:
http://github.com/nickpad/rails-caches-action-patch/tree/master
Turn layout off with render
Thats awkward, but the code below does not turn layout off:
render :action => "short_goal", :layout => nil
you must use false
render :action => "short_goal", :layout => false
print standard-looking messages during migration
Within a migration file you can use the say_with_time method to print out informational messages that match the style of standard migration messages. See the say method also.
say_with_time "migrate existing data" do # ... execute migration sql ... end #=> "-- migrate existing data" #=> " -> 0.0299s"
:null => false
To not allow a column to have a NULL value, pass :null => false. Seems silly, but that’s it.
Readable strftime
%a - The abbreviated weekday name (“Sun”)
%A - The full weekday name (“Sunday”)
%b - The abbreviated month name (“Jan”)
%B - The full month name (“January”)
%c - The preferred local date and time representation
%d - Day of the month (01..31) %H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12) %M - Minute of the hour (00..59)
%p - Meridian indicator (“AM” or “PM”)
%S - Second of the minute (00..60)
%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99) %Y - Year with century
%Z - Time zone name %% - Literal “%” character t = Time.now t.strftime(“Printed on %m/%d/%Y”) #=> “Printed on 04/09/2003” t.strftime(“at %I:%M%p”) #=> “at 08:56AM”
Information on 'ModelName.transaction'
If you are looking for information about:
ModelName.transaction do ... end
or
transaction do ... end
Information on 'ModelName.transaction'
If you are looking for information about:
ModelName.transaction do ... end
or
transaction do ... end
Be careful with overriding dynamic attribute based finders
don’t try something like this:
class Foo < ActiveRecord::Base def self.find_by_bar(*args) foo = super(*args) raise SomeCustomException unless foo foo end end
In newer versions of rails, method_missing defines find_by_bar when you first use it. By calling super, you’re triggering method_missing and overwriting your custom definition! It will work the first time then break! Manually write the call to find!
Custom collection local variable name
Regarding the previous note from hoodow about using :variable_name to create a custom local variable name when rendering a collection with a partial, the argument should be :as instead of :variable_name, so:
render :partial => “video_listing”, :collection => @recommendations, :as => :video
This method has moved
To help anyone else looking, this method is now on the ActionView::Template class.