Flowdock

Recent notes

RSS feed
September 9, 2010
1 thank

bad idea.

Just a note, ypetya’s idea of using a before filter to set the primary key wont scale. transactions will eventually step on each other and probably end up with duplicate key ids, unless you have some other method to ensure uniqueness.

You’d be better off using mysql to generate the default integer primary key and have a secondary string “key” field.

September 9, 2010
0 thanks

Doesn't work? Don't think it ever has.

This doesn’t work for me. I do something like:

create_table :user_follows, :force => true do |t|
  t.references :user
  t.references :followed_user
  t.timestamps
  t.index :user
  t.index :followed_user
end

and I get:

rake aborted!
An error has occurred, all later migrations canceled:

undefined method `index' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x106c02220>

add_index has the same effect.

September 9, 2010
1 thank

takes ActiveRecord object as an arg as well

One undocumented feature, you can do this:

person = Person.first
Person.exists?(person)
# => returns true

This came in handy for me when I needed to see if something belonged to a particular scope.

scope = "created_rails"
person = Person.find_by_name "dhh"
Person.send(scope).exists?(person)
# => returns true

Obviously this relies on you having a named_scope in your Person model called “created_rails”.

September 7, 2010 - (v1_8_6_287 - v1_8_7_72)
1 thank

To illustrate Date class let's calculate days between dates

Code example

date_from = Date.new(2010, 9, 11)
#<Date: 4910901/2,0,2299161>
date_till = Date.new(2010, 11, 12)
#<Date: 4911025/2,0,2299161>
rational_offset = (date_till - date_from)
#Rational62, 1
rational_offset.to_i
#62
September 3, 2010
0 thanks

Don't forget about as

:as is a good but poorly document argument to rendering a collection:

<%= render :partial => 'some_partial', :collection => an_array, :as => :better_name -%>

Which will give you each element of an_array in the partial in a local variable named better_name not some_partial.

September 2, 2010
0 thanks

Set hour and/or minutes

To set the hour and/or the minutes, you can use:

<%= f.datetime_select(:offer_end, :default => { :hour => 23, :minute => 59 }) %>
August 25, 2010 - (>= v2.3.8)
9 thanks

Undocumented :inverse_of option

Support for the :inverse_of option was backported to 2.3.6+.

Here’s the description from the original commit: http://github.com/rails/rails/commit/ccea98389abbf150b886c9f964b1def47f00f237


You can now add an :inverse_of option to has_one, has_many and belongs_to associations. This is best described with an example:

class Man < ActiveRecord::Base
  has_one :face, :inverse_of => :man
end

class Face < ActiveRecord::Base
  belongs_to :man, :inverse_of => :face
end

m = Man.first
f = m.face

Without :inverse_of m and f.man would be different instances of the same object (f.man being pulled from the database again). With these new :inverse_of options m and f.man are the same in memory instance.

Currently :inverse_of supports has_one and has_many (but not the :through variants) associations. It also supplies inverse support for belongs_to associations where the inverse is a has_one and it’s not a polymorphic.

August 25, 2010 - (>= v2.3.8)
2 thanks

Undocumented :inverse_of option

Support for the :inverse_of option was backported to 2.3.6+.

Here’s the description from the original commit: http://github.com/rails/rails/commit/ccea98389abbf150b886c9f964b1def47f00f237


You can now add an :inverse_of option to has_one, has_many and belongs_to associations. This is best described with an example:

class Man < ActiveRecord::Base
  has_one :face, :inverse_of => :man
end

class Face < ActiveRecord::Base
  belongs_to :man, :inverse_of => :face
end

m = Man.first
f = m.face

Without :inverse_of m and f.man would be different instances of the same object (f.man being pulled from the database again). With these new :inverse_of options m and f.man are the same in memory instance.

Currently :inverse_of supports has_one and has_many (but not the :through variants) associations. It also supplies inverse support for belongs_to associations where the inverse is a has_one and it’s not a polymorphic.

August 25, 2010 - (>= v2.3.8)
7 thanks

Undocumented :inverse_of option

Support for the :inverse_of option was backported to 2.3.6+.

Here’s the description from the original commit: http://github.com/rails/rails/commit/ccea98389abbf150b886c9f964b1def47f00f237


You can now add an :inverse_of option to has_one, has_many and belongs_to associations. This is best described with an example:

class Man < ActiveRecord::Base
  has_one :face, :inverse_of => :man
end

class Face < ActiveRecord::Base
  belongs_to :man, :inverse_of => :face
end

m = Man.first
f = m.face

Without :inverse_of m and f.man would be different instances of the same object (f.man being pulled from the database again). With these new :inverse_of options m and f.man are the same in memory instance.

Currently :inverse_of supports has_one and has_many (but not the :through variants) associations. It also supplies inverse support for belongs_to associations where the inverse is a has_one and it’s not a polymorphic.

August 25, 2010 - (>= v2.3.8)
3 thanks

Validating presence of parent in child

When creating a parent and its children using nested attributes, you can use the :inverse_of option on the association to correctly set the parent back references:

class Parent < ActiveRecord::Base
  has_many :children, :inverse_of => :parent
  accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  validates_presence_of :parent
end
August 24, 2010 - (>= v2.3.2)
0 thanks

Deprecated

Instead of using:

session.delete

Now use:

reset_session
August 17, 2010
1 thank

Getting n..end in Rails

Nice one, henning. For anyone using Rails (ActiveSupport) a handy method called #from is also present.

[1, 2, 3, 4, 5].from(2) # => [3, 4, 5]

So our example would be

a.from(i)

It reads a lot better

August 16, 2010
0 thanks

update_all and serialized attributes

If you use update_all to change an attribute marked as serialized ( using ActiveRecord::Base.serialize ), you need to call to_yaml yourself:

User.update_all({ :preferences => { :first_name => 'John',
                                     :last_name  => 'Doe' }.to_yaml })
August 13, 2010
9 thanks

add_to_base in Rails 3

use

model_instance.errors[:base] << "Msg" 

instead of depracated

model_instance.errors.add_to_base("Msg")

for Rails 3

August 13, 2010
0 thanks

Depracated add_to_base

use

model_instance.errors[:base] << "Msg" 

instead of depracated

model_instance.errors.add_to_base("Msg")

for Rails 3

August 13, 2010
1 thank

Confusing log output

If you do a single Rails.cache.read('my_key'), your will usually see in your log something like

Cache read: my_key
Cache read: my_key
Cache write: my_key

Don’t worry about this.

What happens here is this: Before going to memcached, rails will first ask a local MemoryStore cache (which is responsible for the first and third line in the log), before falling through to memcached. This local cache is destroyed after each request.

Source is in activesupport/lib/active_support/cache/strategy/local_cache.rb.

August 11, 2010
3 thanks

In Rails3 use "unscoped" instead

The with_exclusive_scope examples no longer work in Rails3 because with_exclusive_scope is now a protected method which can and should not be used in a controller. Use the new unscoped method instead:

Article.unscoped

For mor details and examples have a look at: http://github.com/rails/rails/commit/bd1666ad1de88598ed6f04ceffb8488a77be4385.

August 9, 2010
2 thanks

When using enumerables

When using enumerables and storing them as strings in the database don’t forget to use .to_s or the select helper won’t automatically select your choice when viewing your data after save.

Exemple:

dates = 1900..Date.today.year
f.select(:year, dates.collect {|d| [d.to_s,d.to_s]}, {:include_blank => "Select"}, {:class => "some_class"} )
August 8, 2010
0 thanks

Path Segments

url_options Returns a hash with path segments.

Example:

{:_path_segments=>{:action=>"show", :location=>"los-angeles-ca", :controller=>"city"}, :script_name=>"", :protocol=>"http://", :host=>"localhost:3000"}
August 5, 2010
0 thanks

Block_given?

Kernel#block_given? can be used to check if yield would be able to call a block.

August 4, 2010 - (>= v2.0.0)
1 thank

Testing Named Scopes

Thanks for the example of testing named_scopes. Being new to Rails, I struggled to find examples that I could understand. Here is another “simple” test for a named_scope

Mine differs slightly from the one above in that I had to remove a set of {} in the :conditions in my test to avoid an “odd number list for Hash” error. I also replace the param-binding “?” with the number I expect to send in as an argument. My test would did know what args[0] was. I got an “undefined local variable” error.

The named scope in my model:

named_scope :up_to_and_including_year, lambda{ |*args| {

:conditions => [“to_char(grad_dt1,‘YYYY’) <= ?”, args[0]] }}

The test:

test "named_scope :up_to_and_including_year" do
  expected_options = { :conditions =>  ["to_char(grad_dt1,'YYYY') <= ?", '2010'] }
  assert_equal expected_options, Sso::CourseTaken.up_to_and_including_year('2010').proxy_options
end
August 3, 2010
1 thank

Inverse function

String#underscore is inverse for the camelize.

“active_record”.camelize.underscore # => “active_record”

August 2, 2010
0 thanks

assert_select negative with regex

(also, you can use instance vars)

assert_select "div#event_#{assigns[event].id}", { :count => 0, :html => /something/ }
August 2, 2010 - (<= v2.3.8)
1 thank

label DOES translate

Maybe it used to not translate but I know it does as of 2.3.8. It is first lookup on the key:

helpers.label.<object_name>.<method_name>

If that doesn’t return anything it will use the human_attribute_name method on ActiveRecord::Base to translated which uses:

activerecord.attributes.<object>.<attribute>

I generally use both of these keys even when I don’t want to translate but just to have a single place where all my adjusted labels are stored.

If any form will need to use the same adjustment given the same object and attribute then I put in on the activerecord key. If the adjustment is form specific then I put it on the helpers key. Here is an example from real working code:

en:
  activerecord:
    attributes:
      "content/rich_text":
        name: Page name
  helpers:
    label:
      content_rich_text:
        testimonial_enabled: Enabled

Note that my AR object is a namespaced object (Content::RichText). In the activerecord key I need to change this to content/rich_text so if can find the correct key and put it in quotes to make it valid YAML. At the helper level on the other hand the namespace simply becomes an _.

July 29, 2010
4 thanks

Getting (n..end) reloaded

You can do

array[n..-1]
July 26, 2010 - (<= v2.3.8)
2 thanks

:confirm, :popup, and :method override :onclick

upplying any combination of :confirm, :popup, and/or :method options to the link_to method results the :onclick option being overridden.

Example:

link_to "Delete", '#', :confirm=>"Are you sure?", :onclick=>"destroyJsFunction()"
# expected output
# => <a href="#" onclick="if(confirm('Are you sure?')) {destroyJsFunction()}; return false;">Delete</a>
# actual output
# => <a href="#" onclick="return confirm('Are you sure?');">Delete</a>

Note that the actual output doesn’t include any mention of the “destroyJsFunction()” passed to the link_to method.

Rails 3 will use unobtrusive JavaScript, and I haven’t tested how that will interact with the :onclick option.

July 26, 2010
0 thanks

Using strings as association names - beware of HashWithIndifferentAccess

If you merge a normal Hash into a HashWithIndifferentAccess, then the keys will convert to strings…

This will likely bite you if the merge is passed to AR find: as netmaniac said “Beware, that using strings as association names, when giving Hash to :include will render errors”.

Beware that params from your controller are HashWithIndifferentAccess like.

July 24, 2010
2 thanks

If your add_index is being ignored in your migration, see this

My add_index command was producing no change in my MySQL 5.0 database:

add_index :designations, [ :scope_type, :scope_id, :role_id, :user_id ], :unique => true

By just adding an index name, the problem was solved:

add_index :designations, [ :scope_type, :scope_id, :role_id, :user_id ], :unique => true, :name => 'my_index'

This happens when the autogenerated index name gets too long. For more info see:

July 23, 2010
2 thanks

To use in testing

If you want to use this in a test, add the following to test_helper.rb:

include ActionDispatch::TestProcess

(If using factory_girl, you can call it in your Factory, like so:

f.photo { fixture_file_upload 'test.png', 'image/png' }
July 23, 2010
3 thanks

Moved in Rails 3

In Rails 3, this has moved to ActionDispatch::TestProcess

(Which means, if you want to use it in a test, you need to add the following to test_helper.rb:)

include ActionDispatch::TestProcess