(image magickをインストールしていない場合はしておく。cloud9にimage magickをインストール)
ここを参照。
1、paperclipで画像を追加するには、以下を追加
has_attached_file :image, styles: { medium: "700x500#", small: "350x250>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
2、rails generate paperclip post imageでmigration作成。
(rails generate paperclip テーブル名 カラム名の順に。当然上の1もhas_attached_fileとvalidates_attachment_content_typeもこれに対応させる)
そのあとrails db:migrate.
*「Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:」が出たら「class AddAttachmentImageToPosts < ActiveRecord::Migration」のところを「ActiveRecord::Migration[5.0]」としてあげるといいらしい。ここを参考
3,posts/_form.html.erbに以下を追加し、imageを投稿できるようにする。また、postsコントローラー内のstrong parameterでimageを受け取ることも可能にする。
image:<%= f.file_field :image %>
def post_params
params.require(:post).permit(:title,:link,:description,:image) ←image追加
end
4,view/postの中の画像を表示させていところに以下のいずれかを書く.
(:medium)や(:small)は1で指定した大きさになる。
<%= image_tag @post.image.url %>
<%= image_tag @post.image.url(:medium) %>
<%= image_tag @post.image.url(:small) %>
以下のようにして、画像をクリックでshowページに飛ばすことも可能
<% @posts.each do |post| %>
<%= link_to (image_tag post.image.url(:small)),post %>
<p><%= link_to post.title,post %></p>
<% end %>