如何添加验证以在Rails应用程序中重新归档?

ipatch

我创建了Rails应用程序,因此可以使用API​​部分。我可以使用curl成功地将文件上传到rails应用程序的数据库,但是我不知道如何将文件类型/内容类型限制为仅CSV。

csv_file.rb#模型

class CsvFile < ActiveRecord::Base
    # attachment :content_type => "text/csv"
    # http://ryanbigg.com/2009/04/how-rails-works-2-mime-types-respond_to/
    attachment :csv, extension: "csv", content_type: "text/csv"
end

csv_files.rb#控制器

class API::V1::CsvFilesController < ApplicationController

  # see http://stackoverflow.com/questions/15040964/ for explanation
  skip_before_filter :verify_authenticity_token

  def index
    @csv_files = CsvFile.all
    if @csv_files
      render json: @csv_files,
        # each_serializer: PictureSerializer,
        root: "csv_files"
    else
      @error = Error.new(text: "404 Not found",
                          status: 404,
                          url: request.url,
                          method: request.method)
      render json: @error.serializer
    end 
  end

  def show
    if @csv_file
      render json: @csv_file,
              # serializer: PictureSerializer,
              root: "csv_file"
    else
      @error = Error.new(text: "404 Not found",
                          status: 404,
                          url: request.url,
                          method: request.method)
      render json: @error.serializer
    end
  end

  # POST /csv_files.json
  def create
    @csv_file = CsvFile.new(csv_params)

    if @csv_file.save
      render json: @csv_file,
        # serializer: PictureSerializer, 
        meta: { status: 201,
          message: "201 Created"},
          root: "csv_file"
    else
      @error = Error.new(text: "500 Server Error",
        status: 500,
        url: request.url,
        method: request.method)
      render :json => @error.serializer
    end
  end

  def update
  end

  def delete
  end

  private

  def csv_params

  end
end
ipatch

因此最终出现了两个问题。

首先,控制器中的强参数应如下所示:

def csv_params
    params.permit(:csv_file)
end

其次,我需要像这样在迁移中添加一列,

add_column :csv_files, :csv_file_id, :string

最后,我能够修改csv_file.rb模型文件并添加以下行。

attachment :csv_file, extension: "csv"

目前,只能将扩展名为的文件.csv上传到API。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何归档包含自定义框架的应用程序?

MediaRecorder Blob可在电子应用程序中归档

如何在Linux for Rails应用程序中添加环境变量?

Rails 5:如何在应用程序模板脚本中添加文件夹和文件

如何在Rails的应用程序中实现stackoverflow的“添加评论”之类的功能?

如何在Rails 4.2应用程序中添加中间件

如何在仅API的Rails应用程序中添加助手

如何在Rails应用程序的ruby中添加404错误页面?

Rails应用程序-如何在API获取请求中添加查询参数?

如何在Qt中重新启动应用程序?

如何在JavaFX中重新加载应用程序?

如何在UWP中重新启动应用程序?

如何从片段重新启动Android中的应用程序

当用户在 Android 中关闭应用程序时如何重新启动应用程序

如何在Shiny应用程序中验证textInput?

如何在iOS应用程序中验证Aadhar号码?

Azure移动应用程序中的应用程序身份验证。如何?

您如何验证从主应用程序启动的应用程序中的令牌是否正确?

如何验证为Rails应用程序中的所有路线定义了控制器动作?

重新启动应用程序时,emberfire 如何维护身份验证会话?

如何使用Java重新验证已在Okta应用程序下登录的用户?

如何在 AOSP 源代码中添加预建应用程序(系统应用程序)

如何重新激活应用程序的GUI?

如何在 Laravel 应用程序中添加回复?

如何在AioHttp中添加运行嵌套应用程序

如何在Arch Linux中添加启动应用程序

如何在“应用程序”菜单中添加项目?

如何在angular 2应用程序中添加reCAPTCHA?

如何添加应用程序在 MATLAB 中运行所需的文件