2

我正在使用带有回形针和 jQuery-File-Upload 的 rails 3,它们都是很棒的宝石,但它们似乎不能很好地配合使用,尤其是对于嵌套模型。

在我的应用程序中,我有两个模型:submissionand upload, and :

**###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:....

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

4

1 回答 1

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
于 2013-04-15T20:53:38.420 回答