[英]Rails not updating record when passed an array of association ids
Am I correct in saying that Rails will handle adding associated has_many items to an object if you pass the params in with a definition like tag_ids as an array of ids?我是否正确地说 Rails 将处理将关联的 has_many 项添加到 object 如果您使用 tag_ids 之类的定义作为 id 数组传递参数?
If so, I'm posting the following to my Item controller:-如果是这样,我将以下内容发布到我的项目 controller:-
{
"title": "Bottle",
"tag_ids": [25, 26]
}
What's happening is that the tag_ids are being ignored.发生的事情是 tag_ids 被忽略了。 I already added tag with id 25, but 26 isn't being included.
我已经添加了 id 为 25 的标签,但没有包含 26。
My controller:-我的 controller:-
# PATCH/PUT /api/items/1
def update
if @item.update(item_params)
render json: @item, include: ['tags']
else
render json: @item.errors
end
end
def item_params
params.require(:item).permit(:name, :tag_ids)
end
Item has_and_belongs_to_many
Tags, and they have a join table of jobs_tags
.项目
has_and_belongs_to_many
标签,它们有一个jobs_tags
连接表。 The association works because I get Tags returned in my response above.该关联有效,因为我在上面的回复中返回了标签。 I can't seem to add them however.
但是,我似乎无法添加它们。 Any idea where I may be going wrong?
知道我哪里可能出错了吗?
Do I need to explicitly add a tag_ids
field to the Item model?我是否需要在项目 model 中显式添加
tag_ids
字段?
The tag_ids
parameter is an array. tag_ids
参数是一个数组。 But permit(:name, :tag_ids)
only permits a single tag_ids
attribute.但是
permit(:name, :tag_ids)
只允许一个tag_ids
属性。
Change the permission to:将权限更改为:
def item_params params.require(:item).permit(:name, tag_ids: []) end def item_params params.require(:item).permit(:name, tag_ids: []) end
See how to permit an array with strong parameters for more details.有关更多详细信息,请参阅如何允许具有强参数的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.