我收到此错误:param is missing or the value is empty: character
。我很困惑。 form_for必定存在问题,但我找不到它。我正在更新Character
控制器中的Users
属性,但这不应该重要吗?
参数:
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"...",
"picturethings"=>{"picture"=>[#<ActionDispatch::Http::UploadedFile:0x000001100087f8 @tempfile=#<Tempfile:/var/folders/19/_vdcl1r913g6fzvk1l56x4km0000gn/T/RackMultipart20150524-4855-1eieu5j.jpeg>,
@original_filename="GOT1.jpeg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"picturethings[picture][]\"; filename=\"GOT1.jpeg\"\r\nContent-Type: image/jpeg\r\n">]},
"commit"=>"Upload pictures",
"callsign"=>"bazzer"}
视图/用户/ edit.html.erb
<%= form_for @character, url: update_pictures_user_path do |f| %>
<%= f.fields_for :picturethings, html: { multipart: true } do |p| %>
<%= p.label :picture %>
<%= p.file_field :picture, multiple: true, name: "picturethings[picture][]" %>
<% end %>
<%= f.submit "Upload pictures" %>
<% end %>
users_controller.rb
def edit
@character = Character.find_by(callsign: params[:callsign])
@user = @character.sociable
@picturething = @character.picturethings.build
end
def update_pictures
@character = Character.find_by(callsign: params[:callsign])
if @character.update_attributes(update_pictures_user_params)
flash[:success] = "Pictures updated"
params[:picturethings]['picture'].each do |p|
@picturething = @character.picturethings.create!(picture: p, character_id: @character.id)
end
render 'edit'
else
render 'edit'
end
end
def update_pictures_user_params
params.require(:character).permit(picturethings_attributes: [:picture])
end
character.rb
belongs_to :sociable, polymorphic: true
has_many :picturethings
accepts_nested_attributes_for :picturethings
user.rb
has_one :character, as: :sociable, dependent: :destroy
的routes.rb
patch '/users/:callsign/update_pictures', to: 'users#update_pictures', as: :update_pictures_user
答案 0 :(得分:0)
您的文件输入名称不正确。如果您查看表单数据:
form-data; name=\"picturethings[picture][]\"; filename=\"GOT1.jpeg\"\r\nContent-Type: image/jpeg\r\n"
没有character
参数。
正确的名称属性如下所示:
character[picturethings_attributes][1][picture][]
当Rails分析表单数据时,它会将其转换为以下哈希:
character: {
picturethings_attributes: {
0 => {
picture : [] # an array of files.
}
}
}
您无需手动指定名称:
<%= form_for @character, url: update_pictures_user_path do |f| %>
<%= f.fields_for :picturethings, html: { multipart: true } do |p| %>
<%= p.label :picture %>
<%= p.file_field :picture, multiple: true %>
<% end %>
<%= f.submit "Upload pictures" %>
<% end %>
Rails会为您提供正确的名称属性。您也不需要手动创建相关记录 - 这是accepts_nested_attributes_for
的全部内容:
def update_pictures
@character = Character.find_by(callsign: params[:callsign])
if @character.update_attributes(update_pictures_user_params)
flash[:success] = "Pictures updated"
render 'edit'
else
render 'edit'
end
end