undefined method `to_key&#39; for #<activerecord::relation []="">

时间:2016-04-04 18:55:24

标签: ruby-on-rails paperclip

I am trying to upload a new file using paperclip.

def new
        @other_font = OtherFont.all
        render :"other_fonts/new"
    end

def create
    @new_font = OtherFont.new(font_params)
    if @new_font.save
        redirect other_fonts_path
    else
        flash[:notice] = "Was not able to upload, try again"
        render :'other_fonts/new'
    end
end

Here is the view

<div id="other fonts">
 <%=form_for @other_font,:html => {:multipart => true} do |f| %>
 <div class="col-2">
  <label>
    <%=f.file_field :file %>
  </label>
   </div>

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

and I get this error

NoMethodError - undefined method `to_key' for #<ActiveRecord::Relation []>: 

I've used paperclip, already for a bit. And I googled the error and people seemed to have about the same code.

1 个答案:

答案 0 :(得分:2)

You need to create a new object. So, your new action should be:

def new
    @other_font = OtherFont.new
    render :"other_fonts/new"
end

Your form expect a new object. But you are giving to him an ActiveRecord::Relation

What is your controller's name? - If it is OtherFontsController, you don't need to call render :"other_fonts/new", and your action should be:

def new
    @other_font = OtherFont.new
end