我已经读完了这个问题how to permit an array with strong parameters但我无法使用params.permit来解决这种情况,来自使用rails 4.2的byebug会话:
如何提取评论参数?
(byebug) params
{"comments"=>"[{\"comment\":\"ndjsnjakldnfljkasdbfhjae\",\"date\":\"2017-07-20 17:14:38\"}]", "format"=>:json, "controller"=>"airis/observations", "action"=>"create", "id"=>"13534543543"}
(byebug) params.permit(:id)
[2017-07-20 19:14:43 +0200] [f2b3d7c8-c84a-43a5-b48f-0f634be49dc7] Unpermitted parameters: comments, format
{"id"=>"13534543543"}
(byebug) params.permit(:comments)
[2017-07-20 19:14:43 +0200] [f2b3d7c8-c84a-43a5-b48f-0f634be49dc7] Unpermitted parameters: format, id
{"comments"=>"[{\"comment\":\"ndjsnjakldnfljkasdbfhjae\",\"date\":\"2017-07-20 17:14:38\"}]"}
(byebug) params.permit(comments: [:comment, :date])
[2017-07-20 19:14:43 +0200] [f2b3d7c8-c84a-43a5-b48f-0f634be49dc7] Unpermitted parameters: format, id
{"comments"=>nil}
(byebug) params.permit(:id, comments: [:comment, :date])
[2017-07-20 19:14:43 +0200] [f2b3d7c8-c84a-43a5-b48f-0f634be49dc7] Unpermitted parameter: format
{"id"=>"13534543543", "comments"=>nil}
甚至是这样:
(byebug) params.permit( :comments => [:comment, :date])
[2017-07-20 19:14:43 +0200] [f2b3d7c8-c84a-43a5-b48f-0f634be49dc7] Unpermitted parameters: format, id
{"comments"=>nil}
答案 0 :(得分:3)
尝试一下:
2.3.1 :034 > JSON.parse(params.permit(:comments)[:comments])
Unpermitted parameters: format, id
=> [{"comment"=>"ndjsnjakldnfljkasdbfhjae", "date"=>"2017-07-20 17:14:38"}]
params.permit(:comments)
只返回"注释" k,v对(删除未经许可的参数,format
和id
):
2.3.1 :035 > params.permit(:comments)
Unpermitted parameters: format, id
=> {"comments"=>"[{\"comment\":\"ndjsnjakldnfljkasdbfhjae\",\"date\":\"2017-07-20 17:14:38\"}]"}
params.permit(:comments)[:comments]
从哈希值中选择:comments
键的值:
2.3.1 :036 > params.permit(:comments)[:comments]
Unpermitted parameters: format, id
=> "[{\"comment\":\"ndjsnjakldnfljkasdbfhjae\",\"date\":\"2017-07-20 17:14:38\"}]"
JSON.parse(params.permit(:comments)[:comments])
将字符串转换为适当的ruby数组。
从那里,您可以使用ruby array
对象执行任意操作。
如果您同时需要:comments
和:id
,则只需:
params.permit(:comments, :id)
Unpermitted parameter: format
=> {"comments"=>"[{\"comment\":\"ndjsnjakldnfljkasdbfhjae\",\"date\":\"2017-07-20 17:14:38\"}]", "id"=>"13534543543"}
获取各个部分:
2.3.1 :038 > params.permit(:comments, :id)[:comments]
Unpermitted parameter: format
=> "[{\"comment\":\"ndjsnjakldnfljkasdbfhjae\",\"date\":\"2017-07-20 17:14:38\"}]"
和:
2.3.1 :039 > params.permit(:comments, :id)[:id]
Unpermitted parameter: format
=> "13534543543"
你可能想把它包装成:
def clean_params
@clean_params ||= params.permit(:comments, :id)
end
所以你可以clean_params[:comments]
和clean_params[:id]
。