Tag: CarrierWave
gem 'carrierwave' gem 'rmagick'
$ bundle exec rails g uploader image
$ bundle exec rails g migration add_image_to_books image:string #=> db/migrate/xxxxx_add_image_to_users.rbが生成される。
$ bundle exec rake db:migrate
class Book < ActiveRecord::Base validates :title, :presence => true # 下記を追加 mount_uploader :image, ImageUploader end
def book_params params.require(:book).permit(:title, :author, :summary, :image) end
<%= form_for(@book) do |f| %> (...省略...) <%= f.label :image %> <%= f.file_field :image %> (...省略...) <% end %>
<% if @book.image? %> <%= image_tag @book.image.s.url %> <% else %> 画像がありません <% end %>
class Book < ActiveRecord::Base validates :title, :presence => true # 下記を追加 mount_uploader :image, ImageUploader mount_uploader :image2, ImageUploader end
def filename # "image1.jpg" or "image2.jpg" "#{mounted_as}.jpg" end