Ruby on Rails Tutorials

Paginate arrays with will_paginate

There may come a time when you wish to paginate an ordinary array of objects, as opposed to an ActiveRecord collection. Thankfully will_paginate supports this out of the box, with very little work.

Firstly, you will need to include the will_paginate array library, which comes with will_paginate. To do this either create or add to an existing initializer in config/initializers/. With all projects I tend to create a file named project_library.rb. Continue reading

How to: Detect if validating inside model

In a model I needed to modify a getter to append a string if a certain attribute evaluated to true. This works great, until I needed to detect the uniqueness of the attribute against a column in the DB through the :uniqueness validator.

The problem

1
2
3
4
5
6
7
8
9
  def label
  new_value = read_attribute(:label)
 
  if self.something == true
    new_label += 'Str'
  end
 
  new_label
end

When validating against the label’s uniqueness the validator will read the label attribute from my custom getter, thus, if a record in the DB has a label of ‘Test’, and our new record has a label of ‘Test’ and self.something evaluates to true, the validator will get ‘TestStr’ from the getter and compare the custom value against the DB. Based on this setup, no match would be found. Continue reading