Domanda

I have a problem with uploading yml file via paperclip. This is my how I try to do it:

In my model I have:

has_attached_file :search_config
validates_attachment_content_type :search_config, content_type: ['text/yaml', 'application/x-yaml', 'text/x-yaml', 'application/yaml', 'text/plain']

In my view:

<%= form_for @search, :html => { :multipart => true } do |f| %> 

<fieldset>
    <legend>Skills</legend>
    <%= hidden_field_tag :type, 'recommendation' %>
    <%= f.file_field :search_config %>
    <%= f.submit 'Save', class: 'btn btn-primary' %>
</fieldset>

In my controller:

def create
    @search = MailingSearch.new(params[:mailing_search])    
    if @search.save
        redirect_to action: :index, notice: 'Your search was successfully created. Search results will be send via email soon.'     
    else
        render action: :new
    end
end

I got an error, that

search_config_content_type=>["is invalid"]

When I try to create a file from console (I'm using the same file):

ms = MailingSearch.new
ms.search_config = File.open('tmp/test.yml')
ms.save

it works. What can be a problem here?

È stato utile?

Soluzione

Use the debugger to check params[:mailing_search] in your controller.

I suspect params[:mailing_search][:search_config].content_type will be application/octet-stream since a .yml file is treated as binary.

Since you don't allow application/octet-stream as a valid content type, that's why you get the error.

When you try through the console the content type is not being overridden by the browser, hence why it works.

In your controller, before building @search, you can reset the content type in the params to the file's MIME type using:

params[:mailing_search][:search_config].content_type = MIME::Types.type_for(params[:mailing_search][:search_config].original_filename).first.content_type

This should preserve text/x-yaml as the content type for the file which you allow as valid.

Altri suggerimenti

You do construct your MailingSearch in completely different ways in your example.

In your controller you constantize something that is probably RecommendationMailingSearch and create an object of this class by passing it params[:mailing_search] which does not seem to be part of your form.

In your manual example you instantiate an object of type MailingSearch and set a File object as the search_config.

It is obvious that you are doing completely different things, how do you expect them to behave in the same way?

Maybe by improving your question such that the object classes match each other and the method calls are more similar you will find the answer on your own.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top