[英]rails strong parameter error on array attribute
i try to post my json to rails server with this request body 我尝试使用此请求正文将json发布到Rails服务器
{"post":{
"user_id": 2,
"title": "kehangatan di pagi hari",
"category": "kehangatan di pagi hari",
"imageposts": [{"imageurl":"DJAWHDAHWDKJHAW DHJAWDHAWDAWDAD"}],
"description":"<p>memang sange</p>"
} }
and this is my posts_params 这是我的posts_params
def post_params
params.require(:post).permit(:title, :user_id, :description, :category, :imageposts => [:imageurl])
end
unfortunately when i make an ajax post i got an error in my terminal 不幸的是,当我发布ajax帖子时,我的终端出现错误
#<ActiveRecord::AssociationTypeMismatch: Imagepost(#42287660) expected, got ActiveSupport::HashWithIndifferentAccess(#30074960)>
i've trying this to my imageposts strong parameter but it doesnt work too 我已经尝试过这对我的imageposts强参数,但它也无法正常工作
imageposts: [:imageurl]
can anybody solve this... 谁能解决这个问题...
The strong params
are fine. strong params
很好。 The problem is that imageposts
is an association, but, just a guess, it is tried to be set as an attribute post.update_attributes(post_params)
问题是
imageposts
是一个关联,但是,仅是一个猜测,尝试将其设置为属性post.update_attributes(post_params)
If you want it to be updated like this, the possible solution is to use accepts_nested_attributes_for
: 如果您希望像这样进行更新,则可能的解决方案是使用
accepts_nested_attributes_for
:
Your model must have something like: 您的模型必须具有以下内容:
class Post
belongs_to :user
has_many :imageposts
accepts_nested_attributes_for :imageposts
end
And the name of params must be imageposts_attributes
instead of just imageposts
: 并且params的名称必须是
imageposts_attributes
而不是imageposts
:
def post_params
params.require(:post).permit(:title, :user_id, :description, :category, :imageposts_attributes => [:imageurl])
end
You are passing multiple images. 您正在传递多个图像。 So you can use
coocoon gem
with accepts_nested_attributes_for
因此,您可以将
coocoon gem
与accepts_nested_attributes_for
for more info https://github.com/nathanvda/cocoon 有关更多信息https://github.com/nathanvda/cocoon
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.