Notes posted to Ruby on Rails
RSS feeddon'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' %> <% } %>
Was removed to a plugin in v 2.0
Is now the auto_complete plugin here:
bug?
beware, update_all silently ignores :limit and :order option in 3.0.8.
I’ve fixed my code temporarily with
update_all "foo=1 where #{myscope.where_values} limit 1"
Set ids when using a collection of values
The trick to getting the helper to populate a unique HTML ID and for rails to recognise a collection is to give the helper a unique ‘name’ and to set the :name symbol to parameter with an array symbol ‘[]’.
<% Cars.each do |c| %> <%= check_box_tag "car_ids[#{c.id}]", c.id, :name => "car_ids[]" %> <% end %>
Typo in matches? example
Iphone example should be def self.matches?(request)
finding without default scopes in rails 3
if you want to find without default scopes in rails 3 and with_exclusive_scope is giving you protected method errors in controllers, use unscoped for a similar purpose
Catching rollback and re-raise exception
In response to wiseleyb, I don’t believe that you could put “rescue” in a transaction block, let alone catching ActiveRecord::Rollback. It would lead you to an “unexpected kRESCUE” error.
I think this is more appropriate.
def start_transaction Company.transaction do # don't forget the bang to make sure it raise # exception or the transaction won't rollback user.save! company.save! x=1/0 return true end # re-raise exception here raise "Exception!" end
Then you could call the method in another place, and it would raise rollback and other exception.
... # would return the "Exception!" if rollback occurs # it would also still trigger another exception other # than rollback. start_transaction ...
Don't Use to_formatted_s(:db) on an Array of IDs
I thought using to_formatted_s(:db) on an array of ids would separate them with commas in a nice way. Wrong. It does, but it also changes the numbers.
Wrong
[60, 271, 280, 283].to_formatted_s(:db) # => "121,543,561,567" # Completely different numbers!
Instead, use the join method:
Right
[60, 271, 280, 283].join(",") # => "60,271,280,283" # Much better
I think this has to do with (:db) being used for formatting dates but I’m not sure.
must be first
A little gotcha I ran into.
This must be defined before you define your relationships.
ie:
class Ticket < ActiveRecord::Base set_table_name 'ticket' belongs_to :customer has_one :account, :through => :customer end
if you do the relationships first it will not use the correct table name on the lookups.
Change to the way the block is handled
At least in 3.0.5, some of the previous examples no longer work: ActionView seems to quietly ignore Array content.
If you were using code of the form
content_tag(:li, nil, :class => 'someClass') { arr.collect { |x| content_tag(:ul, x) } }
it now needs to look like
content_tag(:li, nil, :class => 'someClass') { arr.reduce('') { |c, x| c << content_tag(:ul, x) }.html_safe }
relative_url_root= no longer exists in Rails 3.0
Rails 3.0 does this with scope in config/routes.rb
scope "/exampleapp" do resources :examples root :to => "examples#index" end
Asserting Emails
–setup_mailer.rb in config/initializers –rails g mailer MailerName –methods in mailer_name.rb –files in views/mailer_name –MailerName.method(@object).deliver in object controller
Why gsub!
I notice other adapters use sql.sub!, not sql.gsub! and in fact I had trouble with adding the limit parameter to any query involving nested selects. Replacing sql.gsub! with sql.sub! solved that problem for me. Has anyone else had a similar experience with this method?
In other words, replace:
sql.gsub!(/SELECT/i, 'SELECT B.* FROM (SELECT A.*, row_number() over () AS internal$rownum FROM (SELECT')
With:
sql.sub!(/SELECT/i, 'SELECT B.* FROM (SELECT A.*, row_number() over () AS internal$rownum FROM (SELECT')
logging before filters
If you need to track and log which before filters are called for the purpose of debugging your app/before_filters. Then here’s a suggestion, how this could be accomplished:
customizing text when using label in a form
Instead of the default text Email you can change it to “Primary Email” like this: f.label :email, “Primary Email”
the source is wrong!
in 3.0.5, the source code in line 15 looks like this:
respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
whats wrong with apidock?
Moved to ActiveRecord::Persistence
This isn’t deprecated, it was just moved in Rails 3. See:
reload is deprecated? what's the new alternative?
What’s the recommended alternative to reload for more recent versions of Rails?
After filters are not called when exception occurs
Please note after filters are not executed when an exception occurs. You have to handle these situations explicitly.
How to specify :only_path when non-hash options
When passing in an object, as opposed to a hash, you can’t do this because url_for accepts one argument:
url_for(post, :only_path => true)
Instead, do this:
polymorphic_url(object, :routing_type => :path)
Timestamps
Note that ActiveRecord will not update the timestamp fields (updated_at/updated_on) when using update_all().
Rails 3 validation methods
In rails 3 these have been moved to ActiveModel::Validations::HelperMethods
Method not deprecated
at least not according to the Rails release notes: http://edgeguides.rubyonrails.org/3_0_release_notes.html#validations
Find a random *set* of records (without killing the db)
If you want to find any number of records without sorting your entire table randomly every time, try the solution I posted here:
http://rubyglasses.blogspot.com/2010/05/activerecord-find-in-random-order.html