使用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) %>
这样就能简单的调用了。。。修改missing图片的话,可以如下:
assets/images文件夹下增加
original/missing.png
medium/missing.png
thumb/missing.png
good.rb
:default_url => ":style/missing.png"
这样,当没有图片的时候,会显示对应的app/assets/images/:style路径下的missing.png