使用回形针上传多个图像

时间:2013-12-04 05:58:01

标签: ruby-on-rails paperclip

我是Ruby on Rails的新手。我正在尝试使用回形针上传多个图像。 我有三个模特 *奖励 *专辑 *照片

我有以下映射

模特奖我有

has_one :album

在相册模型中我有

has_many :photos
belongs_to :award

在模特照片中我有

belongs_to :album

因此,当我创建一个新奖项时,它会有一张专辑,而这张专辑会有很多照片。 我在模特照片中使用回形针。

因此,当我创建一个新奖项时,我将如何链接相册和照片,以及我如何保存照片。 在这种情况下如何使用回形针处理多个图像上传?

奖励模式


class Award < ActiveRecord::Base
  attr_accessible :album_id, :award_title, :description, :receiving_date

  #mappings 
  has_one     :album 

  #validate presence of fields
  validates_presence_of :album_id,:title,:description,:receiving_date

  #validate that description has minimum length 3
  validates_length_of :description, :minimum => 3

  #validates that title has length >=3
  validates_length_of :title, :minimum => 3

end

专辑模型


class Album < ActiveRecord::Base
  attr_accessible :description, :title, :award_id

  #mappings 
  has_many    :photos
  belongs_to  :award  

  #validate presence of fields
  validates_presence_of :award_id,:title,:description

  #validate that title has minimum length 3
  validates_length_of :title, :minimum => 3

  #validate that description has minimum length 10
  validates_length_of :description, :minimum => 10

end

照片模特


class Photo < ActiveRecord::Base
  attr_accessible :album_id, :image_url

   #mappings 
  belongs_to  :album

  #validate presence of fields
  validates_presence_of :album_id,:image_url

end

1 个答案:

答案 0 :(得分:0)

您可能希望查看has_many :through关系 - 这意味着您使用一个模型(在您的案例中为相册)作为join model,它将有两个外键 - photo_idaward_id

这就是我要做的事情:

#app/models/album.rb
Class Album < ActiveRecord::Base
    belongs_to :photo, :class_name => 'Photo'
    belongs_to :award, :class_name => 'Award'
    accepts_nested_attributes_for :photo
end

#app/models/award.rb
Class Award < ActiveRecord::Base
    has_many :albums, :class_name => 'Album'
    has_many :photos, :class_name => 'Photo', :through => :albums
    accepts_nested_attributes_for :albums
end

#app/models/photo.rb
Class Photo < ActiveRecord::Base
    has_many :albums, :class_name => 'Album'
    has_many :awards, :class_name => 'Award', :through => :albums
end

这意味着您可以致电@award.photos - 它会显示分配给奖项的相册中包含的所有照片

要将多个图片上传到此,您可以像这样使用accepts_nested_attributes_for

#app/controllers/awards_controller.rb
def new
    @award = Award.new
    @award.albums.build.build_photo
end

def create
    @award = Award.new(award_params)
    @award.save
end

private
def award_params
    params.require(:award).permit(:award, :variables, albums_attributes: [:extra, :vars, photo_attributes: [:photo]])
end

然后,您可以将其添加到上传表单中:

<%= form_for @award do |f| %>
    <%= f.text_field :your_vars %>
    <%= f.fields_for :albums do |a| %>
        <%= a.text_field :extra_var %>
        <%= a.fields_for :photo do |p| %>
             <%= p.file_field :photo %>
        <% end %>
    <% end %>
<% end %>