`

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|

  =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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics