Carrierwave Problem - Files not showing?

青春壹個敷衍的年華 提交于 2019-12-11 16:49:50

问题


<% @company.comments.each do |comment| %>
  <tr>
    <td><%= comment.commenter %></td>
    <td><%= comment.body %></td>
    <td><%= time_ago_in_words(comment.created_at, "Comment") %> ago</td>
    <td><%= comment.commentfile %></td>
  </tr>
<% end %>

Is where i am trying to display the uploaded file from the form below:

<h2>Add a comment:</h2>
<%= form_for([@company, @company.comments.build]) do |f| %>
  <div class="hidden">
    Name:<br />
    <%= f.text_field :commenter, :value => current_user.full_name, :readonly => "readonly" %>
  </div>
  <div class="field">
    Comment:<br />
    <%= f.text_area :body %>
  </div>
  <div class="field">
    <%= f.file_field :commentfile %>  
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

but I don't know whether the file is being saved beacause when i check my public/uploads folder no files appear. And in the view at <%= comment.commentfile %> I get the name of the file i uploaded but no idea where the file is or how i can link to it or whether the file even uploaded at all? starting to think it just inserted a string. My model below.

class Comment < ActiveRecord::Base
  belongs_to :contact
  belongs_to :company
  mount_uploader :commentfile, CommentFileUploader
end

and comment_file_uploader.rb

class CommentFileUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

Please help!

Also to note if i do

u = Comment.new
u.commentfile = params[:file]

in console i get

NameError: undefined local variable or method `params' for main:Object

The migration adding :commentfile

class CreateUploader < ActiveRecord::Migration
  def self.up
    add_column :comments, :commentfile, :string
  end

  def self.down
  end
end

回答1:


The browser has to use a special format to post the upload file data with the form data. You need to make the form multipart.

<%= form_for( [@company, @company.comments.build],
              :html => { :multipart => true } ) do |f| %>

This adds the attribute enctype="multipart/form-data" to the generated HTML, and the browser should then be able to send the uploaded file in a separate part of the message.

If you use Firebug or similar to examine the post data, you'll see that without the multipart encoding enabled, the browser just doesn't send the file data.



来源:https://stackoverflow.com/questions/7110562/carrierwave-problem-files-not-showing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!