Notes for AWD with Rails 4

I checked out from LHU library and grab this book last two days.
And I am going to take some notes here so that I can review it easily in the future, and I also would like to record a story of how n00b wrote their thoughts down.

Creating application with specific Rails version

Here is the example for Rails 4, the command:

Command Line
1
$ rails _4.0.0_ new app_name

Creating your own Rails API documentation

Command Line
1
2
$ cd app_name
$ rake doc:rails

Alternative syntax

%{} is an alternative syntax for double-quoted string literals, convenient for use with long strings:

app/db/seed.rb
1
2
3
4
5
6
Product.create!(title: 'Baozi', description: %{
A
n00b
of
Rails
})

And here why I used exclamation mark (!) for create method? The reason why is that it will raise an exception if records cannot be inserted because of validation failed.

Load specific stylesheet in specific controller

Deponds on controller_name method (API)

app/views/layouts/application.html.erb
1
2
3
<body class="<%= controller.controller_name %>">
<%= yield %>
</body>

Alternate CSS classes for even and odd numbers

Deponds on cycle method (API)

app/views/layouts/application.html.erb
1
2
3
4
5
6
7
<h1>Listing products</h1>
<table>
<% @products.each do |product| %>
<tr class="<%= cycle('list_line_odd', 'list_line_even') %>">
...
</table>

Helpful commands for Git

If you overwrite or delete files, directries that you didn’t mean to, you can always get back by using this command:

Command Line
1
$ git checkout .

On the contrary, if you create folders or files that you didn’t want, try:

Command Line
1
$ git clean -d -f

to get back.

Handling Errors

When we enter example.com/carts/baozi, Active Record will raise a RecordNotFound exception. We can handle it like this:

app/controllers/carts_controller.rb
1
2
3
4
class CartsController < ApplicationController
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
...

app/controllers/carts_controller.rb
1
2
3
4
5
6
private
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
flash[:error] = "Invalid cart."
redirect_to store_url
end

Calculate a sum from the element (API)

app/models/cart.rb
1
2
3
def total_price
line_items.to_a.sum { |item| item.total_price }
end

So the Line_item.rb need total_price method:

app/models/line_item.rb
1
2
3
def total_price
product.price * quantity
end

I am Baozi Wu