未定义的方法`to_key'用于#<class:0x17a6408> -rails-3 </class:0x17a6408>

时间:2011-04-09 18:27:44

标签: ruby-on-rails-3 methods undefined

我在多态上传的表单上遇到了未定义的方法`to_key'的问题。

这是部分形式:

<%= form_for [@parent, Upload], :html => { :multipart => true } do |f|  %>

  <div class="field">
    <%= f.label :document %><br />
    <%= f.file_field :document %>
  </div>

  <div class="actions">
    <%= f.submit "Upload"%>
  </div>
<% end %>

这是控制器:

class UploadsController < ApplicationController
  before_filter :find_parent

  respond_to :html, :js

  def index
    @uploads = @parent.uploads.all unless @uploads.blank?
    respond_with([@parent, @uploads])
  end

  def new
    @upload = @parent.uploads.new unless @uploads.blank?
  end

  def show
    @upload = @parent.upload.find(params[:upload_id])
  end

  def create
    # Associate the correct MIME type for the file since Flash will change it
    if  params[:Filedata]
      @upload.document = params[:Filedata]
      @upload.content_type = MIME::Types.type_for(@upload.original_filename).to_s
      @upload = @parent.uploads.build(params[:upload])
      if @upload.save
        flash[:notice] = "suceessfully saved upload"
        redirect_to [@parent, :uploads]
      else
        render :action => 'new'
      end
    end
  end

  def edit
    @upload = Upload.where(params[:id])
  end
  private


  def find_parent
    classes ||= []
    params.each do |name ,value|
      if name =~ /(.*?)_id/
        @parent =  classes << $1.pluralize.classify.constantize.find(value)
      end
    end
    return unless classes.blank?
  end
end

如果我改变

<%= form_for [@parent, Upload], :html => { :multipart => true } do |f| %>

<%= form_for [parent, Upload], :html => { :multipart => true } do |f| %>

我收到一个新错误:未定义的局部变量或#&lt;#:0x21a30e0&gt;

的方法`parent'

这是错误跟踪:

ActionView::Template::Error (undefined method `to_key' for #<Class:0x2205e88>):
1: <%= render :partial => "uploads/uploadify" %>
2: 
3: <%= form_for [@parent, Upload], :html => { :multipart => true } do |f|  %>
4: 
5: 
6:  <div class="field">

“uploads / uploadify”部分在此要点:https://gist.github.com/911635

任何指针都会有所帮助。感谢

2 个答案:

答案 0 :(得分:7)

答案 1 :(得分:0)

[@ parent,Upload] =&gt; [@parent,:upload]

<%= form_for [@parent, :upload], :html => { :multipart => true } do |f|  %>

<强> UPD

您应该更改地点:upload@parent

<%= form_for [:upload, @parent], :html => { :multipart => true } do |f|  %>