如果我对您的理解正确,您可能需要查看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 %>
这一切都基于实时代码。如果您需要更多帮助,请告诉我!