rails中使用carrierwave上传图片

1.安装

gem install carrierwave

2.更新 Gemfile

gem 'carrierwave'

3.生成uploader

rails generate uploader Avatar

生成文件:app/uploaders/avatar_uploader.rb

4.挂载属性

文件上传后存储的是图片的路径,存储图片路径的字段挂载AvatarUploader.比如model Restaurant有四个属性name 、author 、publish 、picture(用来存放上传图片的路径),在model中加上一行:

class Restaurant< ActiveRecord::Base
    mount_uploader :picture, AvatarUploader
end

5.页面

(1),haml页面

=form_for @restaurant,:html=>{:multipart => ture},:url =>{:action=>‘save_photo’},:method =>"post" do |f|

扫描二维码关注公众号,回复: 486307 查看本文章

  =f.file_field : picture

  =f.submit "保存"

(2)

 <%= form_for @restaurant, :html => {:multipart => true} },:url =>{:action=>‘save_photo’}, do |f| %>
  
    <label>My picture</label>
    <%= f.file_field :picture%>
    <%=f.submit "保存"%>
 
<% end %>

6,controller

 def restaurant

    @restaurant  =Restaurant.new

end

def save_photo

    picture = Restaurant.new

    picture.picture= params[:restaurant][:picture]

end

猜你喜欢

转载自13473996167.iteye.com/blog/2294237
今日推荐