使用嵌套模型的Rails + PaperClip + jQuery-File-Upload

时间:2013-02-12 17:06:53

标签: jquery ruby-on-rails paperclip

我正在使用带有paperclip和jQuery-File-Upload的rails 3,它们都是很棒的宝石,但它们似乎不能很好地结合在一起,特别是对于嵌套模型。

在我的应用中, 我有两个模型:submissionupload,以及:

**###submssion.rb:**

attr_accessible :email, :uploads_attributes
  has_many :uploads, :dependent => :destroy
  accepts_nested_attributes_for :uploads, :allow_destroy => true

**###upload.rb:**
belongs_to :submission
has_attached_file :package
include Rails.application.routes.url_helpers

  def to_jq_upload
    {
      "name" => read_attribute(:package_file_name),
      "size" => read_attribute(:package_file_size),
      "url" => package.url(:original),
      "delete_url" => submission_path(self),
      "delete_type" => "DELETE"
    }
  end

以我的形式:

<%= f.fields_for :uploads do |upload| %>
   <%= upload.file_field :package %>
<% end %>

在我的控制器中:

def create
    @submission = Submission.new(params[:submission])
    respond_to do |format|
      if @submission.save
        format.html { render :json => [@submission.uploads.to_jq_upload].to_json, :content_type => 'text/html',:layout => false }
        format.json { render json: [@submission.uploads.to_jq_upload].to_json, status: :created, location: @upload }
      else
        format.html { render action: "new" }
        format.json { render json: @submission.errors, status: :unprocessable_entity}
      end
    end
  end

但是,每次上传文件时,控制台都会给我:

NoMethodError (undefined method `to_jq_upload' for #<ActiveRecord:....

我的问题是:如何在当前模型的控制器中访问另一个模型的方法?

1 个答案:

答案 0 :(得分:1)

这是一个解决方法:

由于to_jq_upload仅在模型upload中定义,因此您必须指向upload模型才能使用它,在我的情况下,我正在查看最新的上传,这样:

修订后的create方法:

def create
  @submission = Submission.new(params[:submission])
  @upload = @submission.uploads.last
  respond_to do |format|
    if @submission.save
      format.html { render :json => [@upload.to_jq_upload].to_json, :content_type => 'text/html',:layout => false }
      format.json { render json: [@upload.to_jq_upload].to_json, status: :created, location: @upload }
    else
      format.html { render action: "new" }
      format.json { render json: @submission.errors, status: :unprocessable_entity }
    end
end