Rails 5 Extras

In this article, we will discuss how to get the railscast episode 140 to work with Rails 5. You can use find_by with a given value for a table column.

Product.find_by(price: 3)

The output:

Product Load (0.2ms)  SELECT  "products".* FROM "products" WHERE "products"."price" = ? LIMIT ?  [["price", 3], ["LIMIT", 1]]
 => nil

This returns nil when a record is not found. The bang equivalent throws an exception.

Product.find_by!(price: 3)

This results in error:

Product Load (0.1ms)  SELECT  "products".* FROM "products" WHERE "products"."price" = ? LIMIT ?  [["price", 3], ["LIMIT", 1]]
ActiveRecord::RecordNotFound: Couldn't find Product

Rails 5 does not have find_last_by method.

Product.find_last_by(price: 4.99)

This results in error:

NoMethodError: undefined method `find_last_by' for Product (call 'Product.connection' to establish a connection):Class
Did you mean?  find_by

You can join products table with categories and specify the value for a given column that you are querying like this:

Product.joins(:category).where(categories: { :name => 'Clothing' }) 
  Product Load (0.2ms)  SELECT "products".* FROM "products" INNER JOIN "categories" ON "categories"."id" = "products"."category_id" WHERE "categories"."name" = ?  [["name", "Clothing"]]
 => #<ActiveRecord::Relation [#<Product id: 20, name: "Zymosis\n", price: #<BigDecimal:7fa1dbd82e88,'0.2999E2',18(36)>, category_id: 4, description: "Lorem ipsum dolor sit amet, consectetur adipisicin...", created_at: "2016-04-26 18:13:05", updated_at: "2016-04-26 18:13:05">, #<Product id: 21, name: "Zymosimeter\n", price: #<BigDecimal:7fa1dbd81c18,'0.2999E2',18(36)>, category_id: 4, description: "Lorem ipsum dolor sit amet, consectetur adipisicin...", created_at: "2016-04-26 18:13:05", updated_at: "2016-04-26 18:13:05">]>

Rails 5 will give an error if you use the old way of querying.

Product.all(:joins => :category, :conditions => { :categories => { :name => 'Clothing' } })

This results in error:

ArgumentError: wrong number of arguments (given 1, expected 0)

Rails 5 Refactor of Helper.

def admin_area
  if admin?
    content_tag(:div, class: "admin") do
      yield
    end
  end
end

You can test this in the rails console by doing helper.admin_area. You can hardcode admin? method to return true to test the helper.

Summary

In this article, you learned how to use some of the Rails 5 ActiveRecord API and content_tag helper.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.