使用回形针更新模型

时间:2015-10-20 16:30:33

标签: ruby-on-rails angularjs paperclip

我的应用程序的工作流程如下,a使用angularjs前端应用程序,用户创建文章,如果成功,则必须提交图像。

我运行rails generate paperclip article verification_token,创建了以下迁移:

class AddAttachmentVerificationTokenToArticles < ActiveRecord::Migration
  def self.up
    change_table :articles do |t|
      t.attachment :verification_token
    end
  end

  def self.down
    remove_attachment :articles, :verification_token
  end
end

在我的控制器中我创建了一个新动作send_verification_token

def send_verification_token
  @article = current_user.articles.find(params[:id])
  if @article.update_attribute(:verification_token, params[:file])
    render json: @article.id, status: 201
  else
    render json: @article.errors, status: 422
  end
end

但是我得到并且错误,verification_token不是一种方法。 Paperclip已生成verification_token_file_nameverification_token_content_typeverification_token_file_sizeverification_token_updated_at,因此我不确定应该更新哪个属性。

如何更新模型以上传图片?

1 个答案:

答案 0 :(得分:1)

您还需要在模型中定义附件(has_attached_file):

class Article < ActiveRecord::Base
  has_attached_file :verification_token

  validates_attachment_content_type :verification_token, content_type: /\Aimage\/.*\Z/
end

该方法有很多选项,请查看文档:{​​{3}}