模型缺少'avatar_file_name'所需的attr_accessor

时间:2016-04-08 19:38:20

标签: ruby-on-rails paperclip

在生产模式digitalocean上的我的应用程序我配置了Paperclip,但我遇到了这个问题:

I, [2016-04-08T15:17:29.169827 #23709]  INFO -- : Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.6ms)
F, [2016-04-08T15:17:29.171143 #23709] FATAL -- :
Paperclip::Error (CommercialActivity model missing required attr_accessor for 'avatar_file_name'):
  app/controllers/commercial_activities_controller.rb:50:in `create'

commercial_activity.rb

class CommercialActivity < ActiveRecord::Base
   ...
  has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment :avatar, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }
   ...
end

的Gemfile

gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git"

commercial_activities_controller.rb

class CommercialActivitiesController < ApplicationController
   ...
  def create
      ...
     @commercial_activity = current_tradesman.commercial_activities.build(commercial_activity_params)
      ...
    respond_to do |format|
      if @commercial_activity.save
        format.html { redirect_to url_for(controller: :tradesmen, action: :index), notice: 'Commercial activity was successfully created.' }
        format.json { render :show, status: :created, location: @commercial_activity }
      else
        format.html { redirect_to url_for(controller: :tradesmen, action: :index), notice: 'Commercial activity was not created.' }
        format.json { render json: @commercial_activity.errors, status: :unprocessable_entity }
    end

  def commercial_activity_params
   params.require(:commercial_activity).permit(:avatar, ...)
  end
end

设置\环境\ production.rb

...
Paperclip.options[:command_path] = "/usr/bin/"
...

分贝\迁移\ 20160408154436_add_attachment_avatar_to_commercial_activities.rb

class AddAttachmentAvatarToCommercialActivities < ActiveRecord::Migration
  def self.up
    change_table :commercial_activities do |t|
      t.attachment :avatar
    end
  end

  def self.down
    remove_attachment :commercial_activities, :avatar
  end
end

我该如何解决这个问题? 感谢

3 个答案:

答案 0 :(得分:1)

您需要在模型中为avatar_file_name(例如attr_accessor :avatar_file_name)提供列或虚拟属性。 Paperclip会在保存之前将表单值缓存在此字段中。

答案 1 :(得分:0)

作为Anthony的答案的后续行动,并且错误以这种方式阅读,看起来它需要attr_accessor。然而,这对我来说似乎很奇怪,因为我从来没有需要一个让我的回形针图像工作。您是否尝试过为模型attr_accessible

class CommercialActivity < ActiveRecord::Base
  ...
  attr_accessible :avatar
  ...
end

答案 2 :(得分:0)

那么,您确定要运行迁移吗?使用回形针附件运行迁移时,您应该获得以下四项内容:<attachment>_file_name<attachment>_file_size<attachment>_content_type<attachment>_updated_at。好像你错过了所有这些......

以下是文档的链接: https://github.com/thoughtbot/paperclip#usage