LoginSignup
1
0

More than 5 years have passed since last update.

ユーザー登録機能つき投稿サイト④(paperclipで画像を追加する)

Posted at

(image magickをインストールしていない場合はしておく。cloud9にimage magickをインストール)

ここを参照。
1、paperclipで画像を追加するには、以下を追加

model/post.rb
 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を受け取ることも可能にする。

qiita.rb
image:<%= f.file_field :image %>
posts/controller.rb
def post_params
    params.require(:post).permit(:title,:link,:description,:image) ←image追加
end

4,view/postの中の画像を表示させていところに以下のいずれかを書く.
(:medium)や(:small)は1で指定した大きさになる。

posts/show.html.erb
<%= image_tag @post.image.url %>
<%= image_tag @post.image.url(:medium) %>
<%= image_tag @post.image.url(:small) %>

以下のようにして、画像をクリックでshowページに飛ばすことも可能

posts/index.html.erb
<% @posts.each do |post| %>
<%= link_to (image_tag post.image.url(:small)),post %>
<p><%= link_to post.title,post %></p>
<% end %>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0