新手问题 上传图片显示无 display_image 方法

ChileNeverDie · 2020年01月09日 · 最后由 chile 回复于 2020年01月12日 · 2342 次阅读

还是 Rails 教程,错误如图:

已经安装了 imagemagick,添加了 gem 'image_processing', '1.9.3',gem 'mini_magick', '4.9.5' 并且在 models/problem.rb内定义了display_image方法,如代码

class Problem < ApplicationRecord
  belongs_to :user
  has_one_attached :image
  default_scope -> { order(created_at: :desc) } 
  validates :user_id, presence: true 
  validates :ProductID, presence: true
  validates :ProductName, presence: true
  validates :BOL, presence: true, inclusion: {in:['Component','BL'],message:'Must be "Component" or "BL"'} 
  validates :Description, presence, length: {maximum: 500}
  validates :image, content_type: {in: %w[image/jpeg image/gif image/png], message: "must be a valid image format" },
                            size: { less_than: 5.megabytes, message: "should be less than 5MB" } 

  # 返回调整尺寸后的图像,供显示                            
  def display_image 
    image.variant(resize_to_limit: [500, 500])
  end 

end

而且我还发现。。。如果我把 has_one_attached:image 改成 have_many_attached,这个错误就会变成 image 方法找不到,display_image 方法居然就不报错了。。

_problem.html.erb

<li id="problem-<%= problem.id %>">
  <%= link_to gravatar_for(problem.user, size: 50), problem.user %>

  <span class="user"><%= link_to problem.user.name, problem.user %></span>
  <span class="content">
    <%= problem.DetectDate %> | <%= problem.ProductName %>  |  <%= problem.Description %>
    <%= image_tag problem.display_image if problem.image.attached? %>
  </span>

  <span class="timestamp">
    Posted <%= time_ago_in_words(problem.created_at) %> ago.
    <% if current_user?(problem.user) %>
      <%= link_to "delete", problem, method: :delete, data: { confirm: "You sure?" } %>
    <% end %> 
  </span>
</li> 

如果将

<%= image_tag problem.display_image if problem.image.attached? %>

改为

<%= image_tag problem.image if problem.image.attached? %>

不会报错,但是无法控制图片大小。。。

problems_controller.rb

class ProblemsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user, only: :destroy

  def create
    @problem = current_user.problems.build(problem_params)
    @problem.image.attach(params[:problem][:image]) 
    if @problem.save
      flash[:success] = "Problem created!"
      redirect_to root_url
    else
      @feed_items = current_user.feed.paginate(page: params[:page]) 
    end
  end


  def destroy
    @problem.destroy
    flash[:success] = "Problem deleted"
    redirect_to request.referrer || root_url
  end


  private
    def problem_params
      params.require(:problem).permit(:ProductID, :ProductName, :SupplierName, :DetectDate, :Description, :PIC, :BOL, :SolvedOrNot, :image)
    end

    def correct_user
      @problem = current_user.problems.find_by(id: params[:id])
      redirect_to root_url if @problem.nil? 
    end
end

1 楼 已删除

<%= image_tag problem.image, size: '100x100' if problem.image.attached? %>

yfscret 回复

厉害了。。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号