프로그래밍/Ruby & Rails
[Ruby & Rails] 사진 업로드 _paperclip
hyeoke
2018. 8. 9. 01:54
# 레일즈 앱에서 사진업로드 하기
제가 알고 있는 내용으로는 레일즈 앱에서 사진 업로드 기능을 구현할 때에 있어서 paperclip이나 carrierwave gem을 사용하는 것으로 알고 있습니다. 이번 포스팅에선느 paperclip gem을 사용하여 간편하게 사진업로드 기능을 구현해 보겠습니다.
paperclip gem => https://rubygems.org/gems/paperclip
paperclip github => https://github.com/thoughtbot/paperclip/
# Gemfile에 gem 추가하기
# Gemfile
gem 'paperclip', '~> 6.1'
# 터미널
-> $bundle install
# 사진업로드 기능을 넣을 모델에 코드추가
# pin.rb
has_attached_file :image, styles: { medium: "980x980>", thumb: "300x300>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
# 터미널
-> $rails g paperclip pin image
설명: paperclip로 만든 image 칼럼을 pin모델에 추가해라
# Controller에서 Params 추가하기
def pin_params
params.require(:pin).permit(:title, :content, :image)
end
# views 코딩
- _form.html.erb (new)# _form.html.erb의 simple_form 안에 form-group 추가
<div class="form_group">
<%= f.input :image, input_html: { class: 'form-control'} %>
</div>
- show.html.erb
# _show.html.erb
<p><%= image_tag @pin.image.url(:medium), class: "pin_image_show" %></p>