2011-08-18 40 views
0
<% @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 %> 

是我想顯示從下面的表格上傳的文件:載波問題 - 文件沒有顯示?

<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 %> 

,但我不知道該文件是否被保存東陽當我檢查我的公共/上傳文件夾中沒有文件出現。在<%= comment.commentfile %>的視圖中,我得到了我上傳的文件的名稱,但不知道文件的位置或我如何鏈接到該文件,或者文件是否甚至上傳了?開始認爲它只是插入了一個字符串。我的模特如下。

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

和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 

請幫幫忙!

另外需要注意的,如果我做

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

在控制檯我得到

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

遷移補充說:commentfile

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

    def self.down 
    end 
end 
+0

當您提交表單時,日誌中的任何內容? – Chowlett

回答

1

瀏覽器必須使用特殊的格式發佈用表格數據上傳文件數據。您需要將表單分成多個部分。

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

這增加了屬性ENCTYPE =「多部分/格式數據」,以將所生成的HTML,然後瀏覽器應該能夠發送上載文件中的消息的一個獨立部分。

如果您使用Firebug或類似方式檢查發佈數據,您會發現如果未啓用多部分編碼,瀏覽器將不會發送文件數據。