Rails Girls App 評論功能

Created by Janika Liiv, @janikaliiv

替妳的 railsgirls app 加入評論功能。

Step 1: 加入 foreigner gem

加入 Gemfile

gem 'foreigner'

安裝相依套件(如果伺服器正在跑,按 CTRL-C 停止。)

bundle install

Step 2: 建立 comment 鷹架

建立 comment 鷹架,有評論者的姓名(user_name)、評論內容(body)以及評論哪個 idea (idea_id)。

rails g scaffold comment user_name:string body:text idea_id:integer

Step 3: 加入 foreign key 連結

找到這個檔案 db/migrate/YYYYMMDDXXXXXX_create_comments.rb ,在這行之後

t.timestamps
end

加入

add_foreign_key :comments, :ideas

現在給資料庫做遷移:

rake db:migrate

啟動伺服器

rails s

Step 4: 加入模型關係

必須讓 Rails 知道 comments 與 idea 之間的關係(ideas 與 comments)。

一個 idea 可以有很多 comments,但我們得告訴 idea model 這件事才行。

打開 app/models/idea.rb 在這行之後

class Idea < ActiveRecord::Base

加入

has_many :comments

也必須告訴 comment 她屬於單一個 idea。打開 app/models/comment.rb,並在這行之後

class Comment < ActiveRecord::Base

加入

belongs_to :idea

Step 5: 渲染評論的表格及加入現有評論

打開 app/views/ideas/show.html 並在 image_tag 之後

<%= image_tag(@idea.picture_url, :width => 600) if @idea.picture.present? %>

加入

<h3>Comments</h3>
<% @idea.comments.each do |comment| %>
  <div>
    <strong><%= comment.user_name %></strong>
    <br />
    <p><%= comment.body %></p>
  </div>
<% end %>
<%= render 'comments/form' %>

在 app/controllers/ideas_controller.rb 將此行加入 show action。

@comment = @idea.comments.build

打開 app/views/comments/_form.html 並在這行之後

  <div class="field">
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </div>

加入

<%= f.hidden_field :idea_id %>

完成了!現在進去一個 idea 看看,會看到有添加評論的表單,添加個新的評論看看吧。