我正在开发一个设计用户上传许多图片的项目。因此,我想要实现的是用户上传带有描述的图像,然后可以点击按钮"添加另一个"它允许用户添加其他图像和描述,用户可以根据需要添加任意数量的图像。
有人能指出我正确的方向,以实现这项任务吗?
答案 0 :(得分:1)
您需要使用accepts_nested_attributes_for
,这是在提交中包含嵌套属性的标准功能:
#app/models/project.rb
class Project < ActiveRecord::Base
has_many :images
accepts_nested_attributes_for :images, reject_if: :all_blank, allow_destroy: true
end
虽然 - 严格来说 - 您想要的功能是向提交添加多个元素(images#new
),Rails一次只能处理一个记录创建。使用以下内容将更有益:
#config/routes.rb
resources :projects #-> url.com/projects/:id/edit
#app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
def new
@project = Project.new
@project.images.build
end
def edit
@project = Project.find params[:id]
end
def update
@project = Project.find params[:id]
@project.update project_params
end
private
def project_params
params.require(:project).permit(:x, :y, images_attributes: [:attachment])
end
end
#app/views/projects/new.html.erb
<%= render "form", locals: { project: @project } %>
#app/views/projects/edit.html.erb
<%= render "form", locals: { project: @project } %>
#app/views/projects/_form.html.erb
<%= form_for project do |f| %>
<%= f.text_field :x %>
<%= f.text_field :y %>
<%= f.fields_for :images do |i| %>
<% if i.object.new_record? %>
<%= f.file_field :attachment %>
<% else %>
<%= image_tag i.object.attachment.url %>
<%= i.check_box :_destroy %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
以上内容应为您提供@project
的表单,其中包含嵌入的图片。
要添加“额外”字段,您最好查看cocoon
gem或此Railscast:Nested Forms part 1