RoR - 搜索gem以上传文件

时间:2013-12-02 09:34:41

标签: ruby-on-rails ruby image file-upload

我正在搜索允许您上传图像的宝石(如回形针或载波)。但我希望图像与其他图像之间存在关系:

我有一张桌子

我想要一个自己的图像表格,这样我就可以建立has_many belongs_to关系了。

所以有一天有很多图片

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您可能需要查看has_many :through关系。我们使用Paperclip&允许您将多张图像存储到一条记录中:

#app/models/day.rb
Class Day > ActiveRecord::Base
    has_many :day_images, :class_name => "DayImage"
    has_many :images, :class_name => "Image", :through => :day_images, dependent: :destroy

    accepts_nested_attributes_for :day_images, :allow_destroy => true
end

#app/models/day_image.rb
Class DayImage > ActiveRecord::Base
    belongs_to :day, :class_name => "Day"
    belongs_to :image, :class_name => "Image"

    accepts_nested_attributes_for :image, :allow_destroy => true
end

#app/models/image.rb
Class Image > ActiveRecord::Base
    has_many :day_images, :class_name => "DayImage"
    has_many :days, :class_name => "Day", :through => :day_images, dependent: :destroy
end

然后,连接模型将如下所示:

day_images table
id | day_id | image_id | extra attribute | extra attribute | created_at | updated_at

这将允许您使用accepts_nested_attributes_for将图像分配到日模型,如下所示:


嵌套模型

嵌套模型一开始很难做到,但你做得越多就越容易

使用上面列出的模型,您必须添加几个重要因素才能使accepts_nested_attributes_for为您服务。方法如下:

#app/controllers/days_controller.rb
def new
    @day = Day.new
    @day.day_images.build.build_image
end

def create
    @day = Day.new(day_params)
    @day.save
end

private
def day_params
     params.require(:day).permit(:day, :variables, day_images_attributes: [:image_id, :extra_attributes, :in, :join, :model, image_attributes: [:image]])
end

这将允许您创建这样的表单:

#app/views/days/new.html.erb
<%= form_for @day do |f| %>
    <%= f.text_field :day_attribute %>
    <%= f.fields_for :day_images do |day_image| %>
       <%= day_image.text_field :caption %>

       <%= day_image.collection_select(:image_id, Image.where(:user_id => current_user.id), :id, :image_name, include_blank: 'Images') %> --> this will allow you to assign images

       <%= day_image.fields_for :image do |i| %>
           <%= i.file_field :image %> --> uploads new image
       <% end %>
    <% end %>
<% end %>

这完全基于实时代码。如果您需要更多帮助,请告诉我们!