Recent good notes
RSS feed![Default_avatar_30](https://www.gravatar.com/avatar/97339bb1262db04c5a5b63637dd2549b?size=30&default=http://apidock.com/images/default_avatar_30.png)
RE: FALSE: Creates record by given attributes only if table is empty
Dino’s comment was almost certainly due to a misunderstanding of the API, a mistake I made myself the first time I used it, and one I’ve witnessed multiple others make as well.
The fact that this method takes an attributes parameter leads one to think the passed params are the criteria for the selection. At first glance it would appear it would be used like this:
User.first_or_create(email: 'derek@somwhere.com')
Where in reality this would grab the “first” record (say w/ email “john@smith.com”), and change its email to “derek@somwhere.com”, a fairly surprising action that doesn’t obviously fail, leading to some pretty subtle bugs.
In reality it should be used like this:
User.where(email: 'derek@somwhere.com').first_or_create
And the attributes param. isn’t used in 99% of use cases. (If at all - the provision for the block that executes only on create fully duplicates what the attributes parameter can do in a much more obvious way.)
IMHO this is simply a bad API that one just needs to be aware of. But it’s unfair to knock dino for what’s likely a highly common misreading.
![Default_avatar_30](https://www.gravatar.com/avatar/2e5e7d94324be62b6b328ecb067a1913?size=30&default=http://apidock.com/images/default_avatar_30.png)
Creates record by given attributes only if table is empty
This method first searches the table for ANY FIRST RECORD, not the one matching given attributes. If no record is found at all, it creates one using the specified attributes. This might be misunderstood in many cases.
![Default_avatar_30](https://www.gravatar.com/avatar/6ad6fdf4e7ccc06d3002d41158002a07?size=30&default=http://apidock.com/images/default_avatar_30.png)
Very bad documentation
This is terrible documentation. It makes it very hard to understand what the arguments mean.
The signature is
alias_method(p1, p2)
So what do p1 and p2 mean? The description doesn’t refer to them at all, but to new_name and old_name. How are we supposed to know which is which?
And then it gets even worse in the code sample:
alias_method :orig_exit, :exit
From the naming it sounds like the first argument is the original method name.
Documentation is supposed to resolve this kind of confusion, not create it.
![Default_avatar_30](https://www.gravatar.com/avatar/48ae1944e6a82dffa18694663e72c931?size=30&default=http://apidock.com/images/default_avatar_30.png)
Text improvement
Where it says: without loading a bunch of records should say: without loading a bunch of columns/attributes Considering that record usually is a row.
![Default_avatar_30](https://www.gravatar.com/avatar/0b15561003904626e2542dc867aefbba?size=30&default=http://apidock.com/images/default_avatar_30.png)
Opposite of persisted?
So I can find it when I look next time.
![Default_avatar_30](https://www.gravatar.com/avatar/c51384bc4c58b88cf00948e06f14ccf2?size=30&default=http://apidock.com/images/default_avatar_30.png)
Find the First Instance in the Table. If None Exists, Create One.
Specify the data you’re looking for. If it exists in the table, the first instance will be returned. If not, then create is called.
If a block is provided, that block will be executed only if a new instance is being created. The block is NOT executed on an existing record.
Code example
MyStat.where(name: statistic_name).first_or_create do |statistic| statistic.value = calculate_percentage statistic.statistic_type = "percentage" end
![Default_avatar_30](https://www.gravatar.com/avatar/b8da33a5dbfb1a3567cd5d2d3ab783b4?size=30&default=http://apidock.com/images/default_avatar_30.png)
In Rails 4 it DOES return nil, even if the object you try from isn't nil
The try method does not raise a NoMethodError if you call a method that doesn’t exist on an object.
a = Article.new a.try(:author) #=> #<Author ...> nil.try(:doesnt_exist) #=> nil a.try(:doesnt_exist) #=> nil
Note:
a.try(&:doesnt_exist) #=> Raises NoMethodError
![Default_avatar_30](https://www.gravatar.com/avatar/27327ca97512c92e140ad7e5d6d8a212?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/5d092b3a14b92207bf2abdbb8f51f450?size=30&default=http://apidock.com/images/default_avatar_30.png)
Use strings as parameters, not booleans
I just stumbled across this somewhere in our codebase. The first example is faulty, the second one is correct.
= f.check_box :public, {}, true, false # <input id="event_public" name="event[public]" type="checkbox" value="true" />
and:
= f.check_box :public, {}, "true", "false" # <input name="event[public]" type="hidden" value="false" /> # <input id="event_public" name="event[public]" type="checkbox" value="true" />
![Default_avatar_30](https://www.gravatar.com/avatar/e1908e299f9f9fa4938e7e11e2c96f1e?size=30&default=http://apidock.com/images/default_avatar_30.png)
use validates :name, :presence => true instead
validates_presence_of is a holdover from the Rails 2 days.
This is the way it is done now http://guides.rubyonrails.org/active_record_validations_callbacks.html#presence
![Default_avatar_30](https://www.gravatar.com/avatar/349d517e0dcaf44bcb703978b87bf546?size=30&default=http://apidock.com/images/default_avatar_30.png)
Beware - May cause performance issues
A serialized attribute will always be updated during save, even if it was not changed. (A rails 3 commit explains why: http://github.com/rails/rails/issues/8328#issuecomment-10756812)
Guard save calls with a changed? check to prevent issues.
class Product < ActiveRecord::Base serialize :product_data end
bad
product = Product.first product.save
good
product = Product.first product.save if product.changed?
![Default_avatar_30](https://www.gravatar.com/avatar/96cbd04c8b7875711d0b789df4567de8?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/5b2b185c814bb25f2f95a1152e58f033?size=30&default=http://apidock.com/images/default_avatar_30.png)
rest of code is in NilClass#try
If you click “Show source” here, you may get confused. The logic for #try is shared between this method and NilClass#try . Both versions are currently implemented in the file activesupport/lib/active_support/core_ext/object/try.rb .
![Default_avatar_30](https://www.gravatar.com/avatar/4f399ff54aa7e90535716f6c5120897a?size=30&default=http://apidock.com/images/default_avatar_30.png)
Test if an array is included in another
Array
class Array def included_in? array array.to_set.superset?(self.to_set) end end [1,2,4].included_in?([1,10,2,34,4]) #=> true
![Default_avatar_30](https://www.gravatar.com/avatar/170a69e1fece67ca75b97e768dce5585?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/28f2ed7821f4d6b079fc214bbdf31c54?size=30&default=http://apidock.com/images/default_avatar_30.png)
HTML5 data- attributes using RESTful approach
HTML5 specifies extensible attributes like data-foo=“bar” (or as in Twitter Bootstrap data-toggle=“modal”), which poses two problems for Rails.
First, if you’re using symbol notation in link_to to specify attributes, this fails (dash is not a valid symbol character), so
Invalid!
link_to "Edit", @user, :class => "btn", :data-toggle => "modal"
There are two solutions:
-
put the symbols in quotes,
-
use the special :data hash
Solution 1: Quote Symbols
link_to "Edit", @user, :class => "btn", "data-toggle" => "modal"
Solution 2: Use the :data hash
link_to "Edit", @user, :class => "btn", :data => {:toggle => "modal"}
Resulting HTML
<a href="/users/1" class="btn", data-toggle="modal">Edit</a>
The second is minimally documented, but as a hash, can accept multiple values and is perhaps a little cleaner
![Default_avatar_30](https://www.gravatar.com/avatar/c03fdc9fc1f107225b664934e5ff5965?size=30&default=http://apidock.com/images/default_avatar_30.png)
Makes it possible to use a scope through an association
This is a very useful method if you want to to use a scope through an association:
class Book < ActiveRecord::Base scope :available, where(:available => true) end class Author < ActiveRecord::Base has_many :books scope :with_available_books, joins(:books).merge(Book.available) end # Return all authors with at least one available book: Author.with_available_books
See http://asciicasts.com/episodes/215-advanced-queries-in-rails-3 for more info.
![Default_avatar_30](https://www.gravatar.com/avatar/16b8d429e0123bc50ba8ad27cdaa6ff4?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/acce68f8e863176a6b2cf60719f48a36?size=30&default=http://apidock.com/images/default_avatar_30.png)
flash messages
In rails 3.1 the following does not work for me
redirect_to { :action=>'atom' }, :alert => "Something serious happened"
Instead, you need to use the following syntax (wrap with parens)
redirect_to({ :action=>'atom' }, :alert => "Something serious happened")
![Default_avatar_30](https://www.gravatar.com/avatar/4cf647ed8f35defeed6cc04a35889feb?size=30&default=http://apidock.com/images/default_avatar_30.png)
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
![Default_avatar_30](https://www.gravatar.com/avatar/b3bdacd9384d4e7a9335e22cf40473dc?size=30&default=http://apidock.com/images/default_avatar_30.png)
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.
![Default_avatar_30](https://www.gravatar.com/avatar/1704c77d12df42caccc1490333adcb87?size=30&default=http://apidock.com/images/default_avatar_30.png)
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
![Default_avatar_30](https://www.gravatar.com/avatar/93def43f30086e67def068dcec9f6a8d?size=30&default=http://apidock.com/images/default_avatar_30.png)
Replaced by :on => :create
From rails 3,
before_validation_on_create
has been removed and replaced with:
before_validation :foo, :on => :create
![Default_avatar_30](https://www.gravatar.com/avatar/024f6d59fd34ceca04f3fc18a87bdb98?size=30&default=http://apidock.com/images/default_avatar_30.png)
Undocumented :location option
You can use undocumented :location option to override where respond_to sends if resource is valid, e.g. to redirect to products index page instead of a specific product’s page, use:
respond_with(@product, :location => products_url)
![Default_avatar_30](https://www.gravatar.com/avatar/16b8d429e0123bc50ba8ad27cdaa6ff4?size=30&default=http://apidock.com/images/default_avatar_30.png)
How to submit current url
For example to change some kind of param on select change…
<%= form_tag({}, {:method => :get}) do %> <%= select_tag :new_locale, options_for_select(I18n.available_locales, I18n.locale), :onchange => "this.form.submit();" %> <% end %>
![Default_avatar_30](https://www.gravatar.com/avatar/ebc1e0dfecc4345887f07239f102ad3e?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/e556f4b23552aa95b4a3b41a2cb61742?size=30&default=http://apidock.com/images/default_avatar_30.png)
![Default_avatar_30](https://www.gravatar.com/avatar/7fcd2d3243650f8c22ea3612c27b0d20?size=30&default=http://apidock.com/images/default_avatar_30.png)
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
![Default_avatar_30](https://www.gravatar.com/avatar/43006710097182a1a363def690940ab0?size=30&default=http://apidock.com/images/default_avatar_30.png)
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 }
![Default_avatar_30](https://www.gravatar.com/avatar/39140673f8eaec4a3bdf5e76c1fac1eb?size=30&default=http://apidock.com/images/default_avatar_30.png)
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)