"未经许可的参数"使用嵌套属性和has_one:through关系

时间:2014-04-04 12:32:11

标签: ruby-on-rails ruby-on-rails-4

我正在使用Papercrop gem来裁剪我的缩略图。它在我的用户控制器的其他地方工作得很好但是我正在尝试使用has_one:through关系进行裁剪,并且嵌套的表单不是在打球。

一些示例参数:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"t3BsHf6nxAhM9zcRUJfy3nMoLVQAJF/KLbWwqrxeYuk=", "project"=>{"uploaded_image_original_w"=>"960.0", "uploaded_image_original_h"=>"640.0", "uploaded_image_box_w"=>"500", "uploaded_image_crop_x"=>"330", "uploaded_image_crop_y"=>"0", "uploaded_image_crop_w"=>"607", "uploaded_image_crop_h"=>"607", "uploaded_image_aspect"=>"1.0"}, "commit"=>"Save", "profile_name"=>"Benji", "id"=>"1"}

随之而来的错误:

Unpermitted parameters: uploaded_image_original_w, uploaded_image_original_h, uploaded_image_box_w, uploaded_image_crop_x, uploaded_image_crop_y, uploaded_image_crop_w, uploaded_image_crop_h, uploaded_image_aspect

Project.rb

class Project < ActiveRecord::Base
    belongs_to :user

    has_one :thumbnail, :dependent => :destroy
    has_one :image, through: :thumbnail
    accepts_nested_attributes_for :image
end

projects_controller.rb(image_attribute attr_accessors由Papercrop gem完成)

def crop_params
    params.require(:project).permit(image_attributes: [:uploaded_image_original_w, :uploaded_image_original_h, 
                                                     :uploaded_image_box_w, :uploaded_image_crop_x,
                                                     :uploaded_image_crop_y, :uploaded_image_crop_w, 
                                                     :uploaded_image_crop_h, :uploaded_image_aspect])
end

为什么不允许这些属性?

编辑:

添加fields_for改变了我的错误,现在唯一未经许可的参数是“image”

<%= form_for(@project.thumbnail.image, :as => :project,:url => project_thumbnail_path(@user, @project)) do |f| %>
    <%= f.fields_for :image, @project.thumbnail.image do |pf| %>
        <%= pf.cropbox :uploaded_image, :width => 500 %>
    <%= pf.crop_preview :uploaded_image, :width => 150 %>
    <%= pf.submit 'Save' %>
    <% end %>
<% end %>

1 个答案:

答案 0 :(得分:1)

看着你的参数,你并没有将image_attributes:作为一个参数传递:

"project"=>{"uploaded_image_original_w"=>"960.0", "uploaded_image_original_h"=>"640.0", "uploaded_image_box_w"=>"500", "uploaded_image_crop_x"=>"330", "uploaded_image_crop_y"=>"0", "uploaded_image_crop_w"=>"607", "uploaded_image_crop_h"=>"607", "uploaded_image_aspect"=>"1.0"}

您可能未在视图中设置f.fields_for(而只是按原样使用这些元素)。你有表格代码吗?


要使上述参数有效,您需要这些strong_params

params.require(:project).permit(:uploaded_image_original_w, :uploaded_image_original_h, 
                                                     :uploaded_image_box_w, :uploaded_image_crop_x,
                                                     :uploaded_image_crop_y, :uploaded_image_crop_w, 
                                                     :uploaded_image_crop_h, :uploaded_image_aspect)