Recent notes
RSS feedHow to include a “Please select…” (default/prompt) in a grouped dropdown list.
The clue here is that you actually specify the prompt on the select element, and not in the option_groups_from_collection_for_select element.
<%= f.select :post_type_id, option_groups_from_collection_for_select(@categories, :post_types, :name, :id, :name), :include_blank => "Please select..." %>
Hope this helps someone.
Total Unique Elements from Two Arrays
Simple but thought it was worth mentioning:
( [ 1, 2, 3 ] + [ 3, 4, 5 ] ).uniq #=> [ 1, 2, 3, 4, 5 ]
Links and basic explanation
This function, available on any Base derived class, allows eager loading. So when iterating over a result, all the data can be pre-cached, reducing the number of queries from 1+x to 2.
Several ways to use this include:
Post.includes(:author).where(..)
Post.includes([:author, :comments]).where(..)
Post.includes( :comments => :replies ).where(..)
The result is a Relation, so where and other function may be called.
.includes(:comments).to_a is the same as , .find(:all, :includes => :comments)
Some good documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
Apperently one can get similar results by using joins, but i’m not expert on joins, so please ammend and read: http://guides.rubyonrails.org/active_record_querying.html
Recommendations
I would just use the path_to_image. I find that this is what works best. As it says above it can create problems.
Here is my code
Code example
def background_path(background) if background path_to_image background.file_name.normal else path_to_image "background_preview.jpg" end end def flavor_path(flavor) if flavor path_to_image flavor.file_name.normal else path_to_image("flavor_preview.jpg") end end
basic but gets the job done and it does not have problem with my pre built paths which are called image_path
See also: sample
sample randomly picks 1 or n elements from the array
Use kill 0 to find out if process is running
is_running.rb:
#!/usr/bin/env ruby pid = ARGV[0].to_i begin Process.kill(0, pid) puts "#{pid} is running" rescue Errno::EPERM # changed uid puts "No permission to query #{pid}!"; rescue Errno::ESRCH puts "#{pid} is NOT running."; # or zombied rescue puts "Unable to determine status for #{pid} : #{$!}" end
Thanks to http://stackoverflow.com/a/200568/51209
example
[‘one’,‘two’,‘three’].to_sentence # => “one, two, and three”
Need to extend class when using this
I had to dig around to find this out - if you want to use memoize somewhere, like an ActiveRecord model, you need to add
extend ActiveSupport::Memoizable
to the class. This doesn’t seem to be explained anywhere (the only docs are 3 year old blog posts anyway).
Not available
Actually, this method is not available now.(github.com/ruby/ruby/blob/trunk/rational.c#L2352)
Difference in DateTimes ...
Mostly, the database date columns are DateTime instances. Whereas Rails adds several useful utility functions to DateTime (in activesupport), there is some confusing behavior. This is at least somewhat surprising.
Two subtract two DateTime instances, you should always “round” the returned value. Suppose:
d1 = DateTime.now d2 = d1 - 5.days.ago
then, d1 - d2 is a Rational, which tells you the difference between dates only after rounding. Thus, diff_in_days = (d1 - d2).round
This method isn't deprecated
This method was moved to AbstractController::Callbacks, as stated on [1].
It took me a while to figure out ‘what should I use instead before_filter’. Hope this helps anyone that hits the same road I’m in.
index doesn't work
@ssoroka even I’m having same issue. how did you resolve it?
Custom configuration keys
It is nice to know, that you can store any custom configuration key in configure block… E.g.
YourApp::Application.configure do # ... config.my_custom_setting = "QWERTY1234" end
Then you can just access it by calling
YourApp::Application.config.my_custom_setting
Rails 3.1 - Use request.url instead
As request.request_uri has been deprecated, use
request.url
instead.
Change in clone for ActiveRecord objects in ruby-1.9.3
I noticed that cloning an active record object in ruby-1.9.3 and then changing an attribute on the original object will actually change the cloned object as well. This was not the case in ruby-1.9.2.
Examples in a readable format :)
Here are the above examples in a somewhat more readable format:
# Assert a basic route: a controller with the default action (index) assert_routing ‘/home’, :controller => ‘home’, :action => ‘index’ # Test a route generated with a specific controller, action, and parameter (id) assert_routing ‘/entries/show/23’, :controller => ‘entries’, :action => ‘show’, :id => 23 # Assert a basic route (controller + default action), with an error message if it fails assert_routing ‘/store’, { :controller => ‘store’, :action => ‘index’ }, {}, {}, ‘Route for store index not generated properly’ # Tests a route, providing a defaults hash assert_routing ‘controller/action/9’, {:id => “9”, :item => “square”}, {:controller => “controller”, :action => “action”}, {}, {:item => “square”} # Tests a route with a HTTP method assert_routing({ :method => ‘put’, :path => ‘/product/321’ }, { :controller => “product”, :action => “update”, :id => “321” })
Wrapping with select tag
I didn’t knew how to wrap the output with <select> tag. I didn’t want to use raw html, but the doc doesn’t mention another way.
So, here is what I tried and it’s working:
<%= f.select :entry, option_groups_from_collection_for_select(@categories, :entries, :name, :id, :name) %>
I hope this helps anyone. :-)
Specify attachment names
If you want to give your attachment a name, you can do this:
attachment :filename => 'my_file.txt', :body => File.read('/var/null')
It will appear to the recipient as a file named “my_file.txt” rather than something awful like “noname 1”.
Catching and throwing -- don't!
@wiseleyb and @glosakti, neither of your suggestions are necessary, and both are bad practices.
This test:
test "transactions" do assert_raises ZeroDivisionError do User.transaction do 1/0 end end end
passes just fine on its own, with the transaction rolled back as you’d expect. No need to hack something ugly together.
logic in class/id
If you need to place some simple logic in class or like that, I think that best to make it with simple brackets:
Code example
<%= link_to ‘All actions’, switch_action_tab_path, :remote => true, :class => (‘selected’ if @tab == ‘all’) %>
unscoped.all / unscoped.count
At least in console, doing unscoped.all or unscoped.count initially returns expected results but, after you’ve added new records outside of the default_scope those two calls seem to use some cached values.
Therefore it should always be used with the block (as they sort of imply in the doc). unscoped { all } and unscoped {count }
Removed in 3.1.x
This method (and #auto_link_urls) has been removed in Rails 3.1 - other options are out there, such as Rinku, however there is a gem you can use for migration purposes etc, which is rails_autolink: http://rubygems.org/gems/rails_autolink
active_link_to helper gem
You should also have a look at github.com/twg/active_link_to if you need an ‘active’ class on your links.
Adding to the URL
If you want to use polymorphic routing for your object but you also need to specify other stuff like an anchor, you can explicitly generate the polymorphic url with extra options:
form_for @candidate, :url => polymorphic_path(@candidate, :anchor => 'signup')


