我正在尝试将 accepts_nested_attributes_for 与 has_many 关联结合使用,并且遇到很多麻烦......
以下是 user.rb 的简化版:
class User < ActiveRecord::Base
...
has_many :user_permissions
accepts_nested_attributes_for :user_permissions
...
end
我的 user_permission.rb :
class UserPermission < ActiveRecord::Base
belongs_to :user
...
end
我的 users_controller.rb :
class UsersController < ApiController
...
def update
@user.assign_attributes user_params
if @user.save
render partial: 'user', locals: { user: @user }
else
render json: {errors: @user.errors}.to_json, status: 500
end
end
...
private
def user_params
params.require(:user).permit(:first_name, :last_name, user_permissions_attributes: [ :user_id, :resource_id, :can_read, :can_update, :can_create, :can_delete ])
end
end
我正在引用this rails documentation关于如何使用Accept_nested_attributes_for和强参数。
但是,当我&#39; 放置user_params &#39;从users_controller里面我看到了这一点(没有引用user_permissions):
{"first_name"=>"Joe", "last_name"=>"Shmoe"}
以下是我提交给服务器的JSON示例(通过angular $ resource):
{
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions": [
{
"organization_resource_id": 20,
"user_id": 10,
"can_update": true,
"can_read": true
},
{
"organization_resource_id": 21,
"user_id": 10,
"can_create": true,
"can_read": true
}
],
}
返回此JSON:
{
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions": [],
}
我相当有信心这是我的rails层中的一个问题,但这里仅供参考是为了与服务器执行此RESTful交互而创建的有角度的 User.js 服务:
angular.module('slics').service('User', [
'$resource', function($resource) {
return $resource('/api/users/:id', {
id: '@id'
}, {
update: {
method: 'PUT',
isArray: false
}
});
}
]);
真的不确定我在这里缺少什么。看起来似乎不应该提交嵌套属性这么困难......但是我做的研究越多,我就越发现这似乎是一个非常常见的Rails挫折。
如果有任何其他背景/信息有助于包含在我的问题说明中以帮助解决此问题,请随时发表评论,我很乐意提供它!
答案 0 :(得分:1)
好吧,你发布了一个哈希的数组,而不是哈希。
所以这段代码
user_permissions_attributes: [ :user_id, :resource_id, :can_read, :can_update, :can_create, :can_delete ]
将允许这样的结构
{
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions_attributes": [
"organization_resource_id": 20,
"user_id": 10,
"can_update": true,
"can_read": true
]
}
尝试将所有参数列入白名单&#34; user_permissions&#34;
user_permissions_attributes: []
或者查看这篇文章,了解如何使用StrongParams构建高级白名单 http://patshaughnessy.net/2014/6/16/a-rule-of-thumb-for-strong-parameters
答案 1 :(得分:1)
强params期待user_permissions_attributes
,您提交user_permissions
。
强参数与accepts_nested_attributes_for
是分开的(事实上,它与它无关),因此,您定义require!
/ permit
次调用的确属于您的属性提交。
ProTip:为了节省您未来的挫败感,如果您计划通过接受嵌套属性进行更新,您可能也希望允许:id
。
答案 2 :(得分:0)
user_permissions_attributes:[:user_id,:id,:can_read,:can_update,:can_create,:can_delete])permit:id并提交具有索引值的哈希值。
提交给服务的JSON格式
"user": {
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions": {
"0": {
"id": 20,
"user_id": 10,
"can_update": true,
"can_read": true
},
"1": {
"id": 21,
"user_id": 10,
"can_create": true,
"can_read": true
}
}
}