我在rails 4上并使用了carrierwave,我正在尝试让用户上传属于特定对象的照片。父对象是Property,子对象是Photo。我这样做的目的是让一个房产有多张照片。
我希望能够在属性编辑页面上传照片。上传的照片将有一个与property_id相关的外键,因此我可以识别它所属的属性(因此隐藏字段)。
我的问题是我在日志中不断收到“未经许可的参数:照片”消息,这使我无法创建Photo对象。
我的表单看起来像这样
<%= form_for @property, html: { multipart: true } do |f| %>
<%= render "property_form_fields", f: f %>
<%= f.fields_for :photos do |photo| %>
<p>Add photos:</p>
<%= photo.file_field :photo_file_name%>
<%= photo.hidden_field :property_id, :value => @property.id%>
<% end %>
<%= f.submit "Update property", class: 'btn btn-default' %>
<% end %>
照片模特:
class Photo < ActiveRecord::Base
belongs_to :property
mount_uploader :photo_file_name, PhotoUploader
validate :picture_size
private
# Validates the size of an uploaded picture.
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
物业模型
class Property < ActiveRecord::Base
has_many :photos
end
这是我的属性控制器
def edit
@property = Property.find(params[:id])
@photos = Photo.where(:property_id => @property.id)
end
def update
@property = Property.find(params[:id])
if @property.update_attributes(property_params)
flash[:success] = "Property was successfully updated."
redirect_to properties_path
else
flash[:error] = "Property was not created"
render edit_property_path
end
private
def property_params
params.require(:property).permit(:property_name, photos_attributes: [:id, :photo_file_name,:property_id])
end
end
以下是我尝试添加照片时的日志
Started PATCH "/properties/19" for 108.41.84.27 at 2016-07-08 19:59:24 +0000
Processing by PropertiesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ucP...", "property"=>{"property_name"=>"abc", "photos"=>{"photo_file_name"=>#<ActionDispatch::Http::UploadedFile:0x007fe11f0a5598 @tempfile=#<Tempfile:/home/ubuntu/workspace/RackMultipart20160708-6915-1havz2i.jpg>, @original_filename="1554439_686460264746128_2054601640279902551_n.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"property[photos][photo_file_name]\"; filename=\"1554439_686460264746128_2054601640279902551_n.jpg\"\r\nContent-Type: image/jpeg\r\n">, "property_id"=>"19"}}, "commit"=>"Update property", "id"=>"19"}
Manager Load (0.3ms) SELECT "managers".* FROM "managers" WHERE "managers"."id" = ? ORDER BY "managers"."id" ASC LIMIT 1 [["id", 1]]
Property Load (0.2ms) SELECT "properties".* FROM "properties" WHERE "properties"."id" = ? LIMIT 1 [["id", 19]]
Unpermitted parameter: photos
(0.1ms) begin transaction
(0.1ms) commit transaction
Redirected to https://project-apple-mcl282.c9users.io/properties
Completed 302 Found in 12ms (ActiveRecord: 0.7ms)
答案 0 :(得分:0)
您的Property模型需要接受照片的嵌套属性:
class Property < ActiveRecord::Base
has_many :photos
accepts_nested_attributes_for :photos
end