Adding album resource

It is very similar to creating photo model. Each album has a title and has many photos.

$ rails generate model album title:string
    invoke  active_record
    create    db/migrate/20131004132907_create_albums.rb
    create    app/models/album.rb
    invoke    test_unit
    create      test/unit/album_test.rb
    create      test/fixtures/albums.yml

And we can do the association at the same time.

$ rails generate migration AddAlbumIdToPhoto album_id:integer
    invoke  active_record
    create    db/migrate/20131004133355_add_album_id_to_photo.rb

Then we can migrate two migrations at once.

$ rake db:migrate
==  CreateAlbums: migrating =========================================
-- create_table(:albums)
   -> 0.0024s
==  CreateAlbums: migrated (0.0027s) ================================

==  AddAlbumIdToPhoto: migrating ====================================
-- add_column(:photos, :album_id, :integer)
   -> 0.0021s
==  AddAlbumIdToPhoto: migrated (0.0024s) ===========================

Generating controller

$ rails generate controller albums
    create  app/controllers/albums_controller.rb
    invoke  erb
    create    app/views/albums
    invoke  test_unit
    create    test/functional/albums_controller_test.rb
    invoke  helper
    create    app/helpers/albums_helper.rb
    invoke    test_unit
    create      test/unit/helpers/albums_helper_test.rb
    invoke  assets
    invoke    coffee
    create      app/assets/javascripts/albums.js.coffee
    invoke    scss
    create      app/assets/stylesheets/albums.css.scss

The controller

 1class AlbumsController < ApplicationController
 2  def new
 3    @album = Album.new
 4  end
 5
 6  def create
 7    @album = Album.new params[:album]
 8    if @album.save
 9      redirect_to @album
10    else
11      render :new
12    end
13  end
14end

The views/albums/new.html.erb file.

 1<h1>New Album</h1>
 2
 3<%= form_for @album do |f| %>
 4  <p>
 5    <%= f.label :title %> <br>
 6    <%= f.text_field :title %>
 7  </p>
 8
 9  <p>
10    <%= f.submit 'Create Album' %>
11  </p>
12<% end %>

Testing album

What’s next? We’re going to take a look at “Associate photo to album”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content