Sunday, March 9, 2014

Update Blog with Author

Step 1: Set Up a Scaffold

$ rails g scaffold authors name

$ rake db:migrate

Step 2: Add one-to-one relationship into Models

In app/models/post.rb,

class Post < ActiveRecord::Base
  attr_accessible :body, :title, :author_id
  
  belongs_to :author
  
  has_many :comments
  
  validates_presence_of :body, :title
end

In app/models/author.rb,

class Author < ActiveRecord::Base
  attr_accessible :name
  
  has_one :post
  
  validates_presence_of :name
end

Step 3: Adding author_id into Posts table

$ rails g migration add_author_id_to_posts

In db/migrate/..._add_author_id_to_posts.rb,

class AddAuthorIdToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :author_id, :integer
  end
end

$ rake db:migrate

Step 4: Edit the Views in Posts

In app/views/posts/_form.html.erb,

<%= form_for(@post) do |f| %>
  <!-- error message command -->

    <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </div>
  <div class="field">
    <%= f.label :author %><br />
    <%= collection_select(:post, :author_id, Author.all, :id, :name) %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

In app/views/posts/show.html.erb,

  <p id="notice"><%= notice %></p>

  <%= render :partial => @post %>

  by <%= @post.author.name %>
  <br/>

  <%= link_to 'Edit', edit_post_path(@post) %> |
  <%= link_to 'Back', posts_path %>

Return to Internship Note (LoanStreet)
Previous Episode: Adding Delete Comment Feature into Blog Post
Next Episode: Update Blog with Favourites (Part 1)

0 comments:

Post a Comment