2012-12-14 32 views
0

我试图将一个动态数量的图片添加到名为“组件”的元素。 环顾四周,我创建了这个代码:Rails回形针 - 添加动态多个图像

component.rb

class Component < ActiveRecord::Base 
    has_many :images 
    accepts_nested_attributes_for :images, :allow_destroy => true 
end 

image.rb

class Image < ActiveRecord::Base 
    attr_accessible :component_id, :photo_file_size 

    belongs_to :component, :foreign_key => :component_id 
    has_attached_file :photo, 
    :styles => { 
     :thumb => "75x75>", 
     :small => "200x200>" 
    } 
end 

_form.html.erb

<%= form_for setup_component(@component) , :html => { :multipart => true } do |f| %> 
... 
    <h2> PHOTOS </h2> 
<% f.fields_for @component.images.build do |p| %> 
     <h2>Photo</h2> 
      <p><%= f.label :data %><br /><%= f.file_field :data %></p> 
<% end %> 

application_helper.rb

def setup_component(comp) 

    return comp.images.build if comp.images.empty? 
end 

所以我得到当我尝试去形成以下错误:

undefined method `images_path' 
+0

哪里'images_path'出现在你的代码? –

+0

ID未显示。但是当我评论这一行时,问题就消失了: 'return comp.images.build if comp.images.empty?'。 现在我在控制器中这样做,它的工作原理,但是当我提交表单时,它崩溃了。所以更多的是错误的。 – user1573607

+0

通常,'fields_for'用于关联:'fields_for @ component.images'。这有帮助吗? –

回答

0

你得到你的images_path错误,因为你不设置窗体右上

为什么这段代码不在你的控制器中?

def setup_component(comp) 
    return comp.images.build if comp.images.empty? 
end 

你的form_for对象需要有一个明确的变量定义,以允许创建一个ActiveRecord对象。 Rails将你分配给form_for的变量,并用它来为表单建立一个完整的结构,并返回一个返回路径(如果有错误)。目前,你的表单构建一个新的图像,这就是它返回images_path错误的原因。

<%= form_for setup_component(@component) 

你会更好写这样的:

#app/controllers/component_controller.rb 
def new_image 
    @comp = Comp.new 
    @comp.images.build 
end 

那么你的表格可以从你的/新/路由被调用,从而使轨真正的航线为您带来回。


其次,在窗体中有这样的:

<% f.fields_for @component.images.build do |p| %> 
     <h2>Photo</h2> 
      <p><%= f.label :data %><br /><%= f.file_field :data %></p> 
<% end %> 

这应该更改为:

<%= f.fields_for :images do |p| %> 
     <h2>Photo</h2> 
      <p><%= p.label :data %><br /><%= p.file_field :data %></p> 
<% end %>