简体   繁体   English

数组属性上的rails强参数错误

[英]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 gemaccepts_nested_attributes_for

for more info https://github.com/nathanvda/cocoon 有关更多信息https://github.com/nathanvda/cocoon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM