我正在玩Rails 4.x beta并尝试使用carrierwave获取嵌套属性.不确定我正在做的是正确的方向.搜索后,最后查看导轨源和强参数,我发现了下面的注释.
Run Code Online (Sandbox Code Playgroud)# Note that if you use +permit+ in a key that points to a hash, # it won't allow all the hash. You also need to specify which # attributes inside the hash should be whitelisted.
所以它说你必须在has中指定每一个单独的属性,我尝试了以下内容:
帕拉姆的例子:
{"utf8"=>"?",
"authenticity_token"=>"Tm54+v9DYdBtWJ7qPERWzdEBkWnDQfuAQrfT9UE8VD=",
"screenshot"=>{
"title"=>"afs",
"assets_attributes"=>{
"0"=>{
"filename"=>#<ActionDispatch::Http::UploadedFile:0x00000004edbe40
@tempfile=#<File:/tmp/RackMultipart20130123-18328-navggd>,
@original_filename="EK000005.JPG",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"screenshot[assets_attributes][0][filename]\"; filename=\"EK000005.JPG\"\r\nContent-Type: image/jpeg\r\n">
}
}
},
"commit"=>"Create Screenshot"}
Run Code Online (Sandbox Code Playgroud)
调节器
def screenshot_params
params.require(:screenshot).permit(:title,
:assets_attributes => [:filename => [:@tempfile,:@original_filename,:@content_type,:@headers]
Run Code Online (Sandbox Code Playgroud)
以上不是"工作"(它不触发载波)但是当我使用我发现的标准嵌套示例时,我不再收到错误(未经许可的参数:文件名):
def screenshot_params
params.require(:screenshot).permit(:title, assets_attributes: :filename)
Run Code Online (Sandbox Code Playgroud)
如果有人能提供帮助就会很棒.我无法找到嵌套了一个指向哈希的键的示例.
我有一个UploadActiveModel类,它有一个属性:filename.由于只有一个属性,因此在表单中将该字段留空会导致在我的控制器中使用以下代码时出现错误:
class UploadsController < ApplicationController
def create
@upload = Upload.new(upload_params)
# ...
end
private
def upload_params
params.require(:upload).permit(:filename)
end
end
Run Code Online (Sandbox Code Playgroud)
我提出的最好的解决方法是rescue在upload_params方法中,例如:
def upload_params
params.require(:upload).permit(:filename) rescue ActionController::Parameters.new
end
Run Code Online (Sandbox Code Playgroud)
或者,我想我可以添加一个隐藏字段,以确保该filename字段始终设置为某种东西,无论如何,例如:
= simple_form_for upload do |f|
= f.input :filename, as: :hidden, input_html: { value: '' }
= f.input :filename, as: :file
= f.submit 'Upload'
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来处理用户没有填写任何表单属性?
我需要将图像上传到我的电影收藏应用程序我使用carrierwave来执行此操作(按照railscasts步骤)
步骤1我将gem'carrierwave','〜> 0.9'添加到我的Gemfile然后运行bundle步骤2 rails g uploader image然后rails g scaffold filmes name moviestype rake db step 3 rails g migration add_image_to_filmes image:string然后rake db
其他步骤与railscast相同
在我的电影模型中
attr_accessible :name, :moviestype, :image
mount_uploader :image, ImageUploader
Run Code Online (Sandbox Code Playgroud)
在我的_form.html.erb中
<%= form_for @filme, :html => {:multipart => true} do |f| %>
<% if @filme.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@filme.errors.count, "error") %> prohibited this filme from being saved:</h2>
<ul>
<% @filme.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field"> …Run Code Online (Sandbox Code Playgroud)