使用params手动保存文件,不带脚手架

时间:2012-12-05 12:51:21

标签: hash rubygems ruby-on-rails-3.2 paperclip params

我是rails的新手,我正在处理paperclip gem并希望保存从paperclip保存的简单文件。 我的My模型如下: -

    class UserAttachment < ActiveRecord::Base
          attr_accessible :email, :user_id, :attached_file
          has_attached_file :attached_file
          validates_attachment_presence :attached_file   
          validates_attachment_size :attached_file, :less_than => 20.megabytes   
        end

调用表单的控制器操作: -

class HomeController < ApplicationController
  def index
  @uattachment = UserAttachment.new
  end
end

表单所在的索引视图代码

<%= form_for @uattachment, :url => attachment_get_link_path, :html => { :method => :post, :id => 'attachment_form', :multipart => true }, :remote => true do |f| %>
    <%= f.email_field :email, :value=>nil, :placeholder => "Enter your email here", :required => true %><br />
    <%= f.file_field :attached_file %>
    <%= f.submit "Submit" %>
<% end %>

我想使用以下类型的代码来保存数据: - (下面的代码不是正确的代码,在我的应用程序中告诉我想做什么是一种激动。)

@uattachment = UserAttachment.new
@uattachment = params[:user_attachment]
@uattachment.save

收到的参数如下: -

(rdb:6) pp params
{"utf8"=>"✓",
 "authenticity_token"=>"dfjaskldjadslgjsoidruts48589034lsker=",
 "user_attachment"=>
  {"email"=>"testing@email.com",
   "attached_file"=>
    #<ActionDispatch::Http::UploadedFile:0x007fcb58682ba0
     @content_type="image/jpeg",
     @headers=
      "Content-Disposition: form-data; name=\"user_attachment[attached_file]\"; filename=\"someimage.jpg\"\r\nContent-Type: image/jpeg\r\n",
     @original_filename="800px-Kinnaur_Kailash.jpg",
     @tempfile=#<File:/tmp/RackMultipart20121205-8432-1fc1kpi>>},
 "commit"=>"Submit",
 "controller"=>"attachment",
 "action"=>"get_link"}

1 个答案:

答案 0 :(得分:1)

得到了捕获,非常简单,我从脚手架作业中检查了它,

def index
  @uattachment = UserAttachment.new(params[:user_attachment])
  @uattachment.save
end

你得到的回答是“真实的”。