如何使用paperclip gem调整图像大小

时间:2016-08-17 19:25:36

标签: ruby-on-rails ruby

我想通过回形针使用头像。在教程中使用gravatar

messages_helper.rb

 def recipients_options(chosen_recipient = nil)
 s = ''
 User.all.each do |user|
 s << "<option value='#{user.id}' 
               data-img-src='#{gravatar_image_url(user.email, size: 50)}' 
               #{'selected' if user == chosen_recipient}>
               #{user.name}</option>"
 end
 s.html_safe
 end

我改变了这段代码并且工作正常。

module MessagesHelper
  def recipients_options(chosen_recipient = nil)
   s = ''
   User.all.each do |user|
    s << "<option value='#{user.id}' data-img-src='#{user.avatar.url(:thumb)}'  
               #{'selected' if user == chosen_recipient}>#{user.username}</option>"
   end
   s.html_safe
  end


end

new.html.erb

<div class="form-group">
  <%= label_tag 'recipients', 'Choose recipients' %>
  <%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it ' %>
</div>

user.rb

 has_attached_file :avatar, :styles => { :medium => "150x150>", :thumb => "30x30#" }, default_url: "https://s3.amazonaws.com/myinstick/logo/instagram-icon.png"
 validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

但是!如果用户没有头像,则使用图像回形针默认。并且它没有缩放,它看起来很大。如何设置样式或大小。

it looks like this

2 个答案:

答案 0 :(得分:1)

在您的模型中:

  has_attached_file :avatar, 
        :styles => { thumb: "100x100#", medium: "300x300#", large: "900x500#"}

或您想要的任何尺寸。 #用于裁剪。它将选择图像的中心并从那里裁剪指定的高度和宽度。如果您不想进行裁剪,也可以使用默认的> ...并在您的视图中:

<%= image_tag @user.avatar.url(:medium) %>

答案 1 :(得分:0)

我解决了这个问题。下拉列表使用 jquery.image-select.js

(function($) {

// Image template, this can be overridden from the constructor (options.template),
// must contains {src} placeholder. Ther eare two class names 'chose-image' or 'chose-image-small', modifiy in CSS
var fn_template = '<img class="{class_name} " src="{url}" />';

// Store the original 'chosen' method
var fn_chosen = $.fn.chosen;........

我可以为所有图像设置类,比如

 var fn_template = '<img class="{class_name} image-circle-minisize" src="{url}" />';

一切正常