使用paperclip這個gem,參考以下鏈接:
https://github.com/thoughtbot/paperclip
Gemfile
gem "paperclip", "~> 4.2"
rails g paperclip good good_image
rake db:migrate
models/good.rb
has_attached_file :good_image, :styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :good_image, :content_type => /\Aimage\/.*\Z/
controllers/goods_controller.rb
def good_params
params.require(:good).permit(:name, :price, :description, :discount, :good_image)
end
views/goods/_form.html.erb
<%= form_for(@good, html: {multipart: true}) do |f| %>
...
<%= f.file_field :good_image %>
...
<% end %>
views/goods/show.html.erb
<%= image_tag @good.good_image.url %>
<%= image_tag @good.good_image.url(:medium) %>
<%= image_tag @good.good_image.url(:thumb) %>
這樣就能簡單的調(diào)用了。。。修改missing圖片的話,可以如下:
assets/images文件夾下增加
original/missing.png
medium/missing.png
thumb/missing.png
good.rb
:default_url => ":style/missing.png"
這樣,當沒有圖片的時候,會顯示對應(yīng)的app/assets/images/:style路徑下的missing.png