访问操作控制器参数的值



我需要访问attachments值,我找不到路 它说允许假,虽然在强参数中是允许的......

<ActionController::Parameters {
"utf8"=>"✓", 
"authenticity_token"=>"wMY3FheLXzezCBO8phfst85DGdSBmVRl+nljAUYviYxZsWXMXC+Rcddit3XaNNikaGTvdLH+rx5ZNh6bY31Yzw==", 
"finished_guitar"=><ActionController::Parameters 
{ "title"=>"my super title",
"description"=>"and my awsome description"
} permitted: false>,
"commit"=>"Create Finished guitar",
"params"=>{
"attachments"=>[{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fcfa084fa90 @tempfile=#<Tempfile:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20180902-64552-9bms50.jpg>,
@original_filename="image_1.jpg",
@content_type="image/jpeg", 
@headers="Content-Disposition: form-data; name="params[attachments][][image]"; 
filename="image_1.jpg"rnContent-Type: image/jpegrn">
}]
},"controller"=>"finished_guitars", "action"=>"create"} permitted: false>

我的控制器:

class FinishedGuitarsController < ApplicationController
def index
@finished_guitars = FinishedGuitar.all
end
def show
@finished_guitar = FinishedGuitar.find(params[:id])
end
def new
@finished_guitar = FinishedGuitar.new
@attachments = @finished_guitar.attachments.build
end
def create
@finished_guitar = FinishedGuitar.new(finished_guitar_params)
if @finished_guitar.save
unless params[:attachments].nil?
params[:attachments]['image'].each do |a|
@finished_guitar = @finished_guitar.attachments.create!(:image => a, :finished_guitar_id => @finished_guitar.id)
end
end
render json: { finishedGuitardId: @finished_guitar.id, attachments: @finished_guitar.attachments_attributes }, status: 200
else
render json: { error: @finished_guitar.errors.full_messages.join(", ") }, status: 400 
end
end
private
def finished_guitar_params
params.require(:finished_guitar).permit(:title, :description, attachments_attributes: [:id, :image, :finished_guitar_id])
end
end

更新

我只是在添加_form.html.erb

<div class="content">
<%= simple_form_for @finished_guitar, html: {multipart: true, id: "my-dropzone", class: "dropzone" } do |f| %>
<%= f.input :title %>
<%= f.input :description %>
<div class="dz-message needsclick">
<h3>Drop file here</h3> or
<strong>click</strong> to upload
</div>
<div class="fallback">      
<br><br>
<%= f.simple_fields_for :attachments do |ff| %>
<%= ff.input_field :image, as: :file, multiple: true, name: "finished_guitar[attachments_attributes][][image]" %>
<% end %>
</div>
<br><br>
<%= f.button :submit, class: "btn btn-primary" %>
<% end %>     
</div>

如果我从<%= simple_form_for @finished_guitar, html: {multipart: true, id: "my-dropzone", class: "dropzone" } do |f| %>中删除"my-dropzone", class: "dropzone",我可以上传我的文件

它说name=params[attachments][][image],它接缝你有类似的东西:

params[:params][:attachments]

我建议你使用rails-pry或byebug,停止操作中的执行,你可以很容易地检查参数哈希并做一些像params.keysparams[:params]的事情,看看实际存在什么。

最新更新