使用Rails将多个资源添加到资源

时间:2013-03-31 06:51:06

标签: ruby-on-rails paperclip

我正在构建一个房地产网络应用程序,每个广告应该有无限数量的图片(资产)。

在广告#新表单中,我想让用户可以选择上传尽可能多的图片。

我创建了一个具有__资产的广告模型。资产是一种模型,用于保存图片的回形针。

这是代码:

class Asset < ActiveRecord::Base
  attr_accessible :picture
  has_attached_file :picture, :styles => { :large => "600x600", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

  belongs_to :ad
end


class Ad < ActiveRecord::Base
  attr_accessible :contact_cell, :description, :price, :title, :user_id

  belongs_to :user

  has_many :assets, dependent: :destroy
end

如果我想让用户在他/她提交表单之前添加无限量的照片,那么form_for应该如何?

1 个答案:

答案 0 :(得分:0)

如果你想用html5做,你可以通过做类似的事情轻松做到(重要的是要注意的是,在html5上你可以添加属性multiple = true,这将为你创建一个多重上传):

<%= simple_form_for(@ad, html: { multipart: true }) do |f| %>
  <%= f.input :contact_cell %>
  <%= f.input :description %>
  <%= f.input :price %>
  <%= f.input :title %>
  <%= file_field_tag('ad_assets_picture', multiple: true, name: "ad[assets_attributes][][picture]") %>
  <%= f.button :submit %>
<%- end %>

否则你可以按照嵌套的表单示例,有一个nice webcast about it