【发布时间】:2014-06-30 22:30:08
【问题描述】:
我有一个表单,其中有我试图保存的“嵌套属性”。我今天下午才知道这些,而且我是 Rails 新手,所以我会尽力解释这一点。
我有两个模型,画廊和展览照片。前者“has_many”和后者“belongs_to”彼此。 “展览照片”通过画廊控制器上传。
我可以提交表单,但嵌套属性(图像)根本没有被保存。
这是有问题的控制器
def update
@gallery = Gallery.friendly.find params[:id]
if @gallery.update(gallery_params)
redirect_to '/'
else
render '/new'
end
end
def edit
@gallery = Gallery.friendly.find params[:id]
end
private
def gallery_params
params.require(:gallery).permit(:title, exhibition_images: [:image])
end
之所以更新和编辑而不是新建,是因为 Gallery 模型的一个实例是在其父模型创建时创建的。
这里是编辑表格
<%= bootstrap_form_for(@gallery, layout: :horizontal, label_col: "col-sm-2", control_col: "col-sm-10") do |f| %>
<%= f.text_field :title %>
<%= f.fields_for :exhibition_images do |f| %>
<%= f.file_field :exhibition_image, help: "Ensure images are minimum 400x400px" %>
<% end %>
<%= f.submit "Create/Update", class: "btn btn-primary" %>
<% end %>
画廊模型
class Gallery < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :guide
has_many :exhibition_images
accepts_nested_attributes_for :exhibition_images
展览模型
class ExhibitionImage < ActiveRecord::Base
belongs_to :gallery
has_attached_file :image, styles: { small: "100x100", guide: "500x500" }
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
现在我确信有一种更好、更清洁的方法可以做到这一点,如果有人可以解释或展示,我将不胜感激。但最重要的是,我想让这件事发挥作用。
更新
添加了开发日志
Started PATCH "/galleries/martin-bates-geoff-brindle" for 127.0.0.1 at 2014-07-01 00:27:48 +0100
Processing by GalleriesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"JzFnQgV4ZBoh176xdphPtH/AJsm/BE1N+LWtTUTOgx8=", "gallery"=>{"title"=>"BLAH BLAH BLAH", "exhibition_images_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x00000104355c28 @tempfile=#<Tempfile:/var/folders/ns/ry6z7jfd6qg6j8xr2q6dw0yc0000gn/T/RackMultipart20140701-28390-1lfmco8>, @original_filename="oasis.gif", @content_type="image/gif", @headers="Content-Disposition: form-data; name=\"gallery[exhibition_images_attributes][0][image]\"; filename=\"oasis.gif\"\r\nContent-Type: image/gif\r\n">}}}, "commit"=>"Create/Update", "id"=>"martin-bates-geoff-brindle"}
Guide Load (0.9ms) SELECT "guides".* FROM "guides" WHERE (date_starting > '2014-06-30 23:27:48.391845') ORDER BY "guides"."date_starting" ASC
Course Load (0.3ms) SELECT "courses".* FROM "courses" ORDER BY "courses"."id" DESC LIMIT 2
YearlyGuide Load (0.3ms) SELECT "yearly_guides".* FROM "yearly_guides" ORDER BY "yearly_guides"."id" DESC LIMIT 1
Gallery Load (0.2ms) SELECT "galleries".* FROM "galleries" WHERE "galleries"."slug" = 'martin-bates-geoff-brindle' ORDER BY "galleries"."id" ASC LIMIT 1
Unpermitted parameters: exhibition_images_attributes
(0.1ms) BEGIN
(0.1ms) COMMIT
Redirected to http://localhost:5000/
Completed 302 Found in 7ms (ActiveRecord: 1.9ms)
【问题讨论】:
标签: ruby-on-rails ruby forms parameters