【问题标题】:rails strong parameter error on array attribute数组属性上的rails强参数错误
【发布时间】:2017-07-26 05:46:48
【问题描述】:

我尝试使用此请求正文将我的 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>"
  } }

这是我的posts_params

  def post_params
    params.require(:post).permit(:title, :user_id, :description, :category, :imageposts => [:imageurl])
  end

不幸的是,当我发布 ajax 帖子时,我的终端出现错误

#<ActiveRecord::AssociationTypeMismatch: Imagepost(#42287660) expected, got ActiveSupport::HashWithIndifferentAccess(#30074960)>

我已经在我的 imageposts 强参数上尝试了这个,但它也不起作用

imageposts: [:imageurl]

谁能解决这个问题...

【问题讨论】:

  • 发布收到的params(查看服务器日志)

标签: ruby-on-rails ruby activerecord active-model-serializers


【解决方案1】:

strong params 很好。问题是imageposts是一个关联,但是,只是猜测,它被尝试设置为属性post.update_attributes(post_params)

如果你希望它像这样更新,可能的解决方案是使用accepts_nested_attributes_for

您的模型必须具有以下内容:

class Post
  belongs_to :user
  has_many :imageposts
  accepts_nested_attributes_for :imageposts
end

并且参数的名称必须是imageposts_attributes 而不仅仅是imageposts

def post_params
  params.require(:post).permit(:title, :user_id, :description, :category, :imageposts_attributes => [:imageurl])
end

【讨论】:

  • 它的工作,但它回复了=> {“imageposts.post”:[“必须存在”]}。而我有一个 post_id 属性
  • 嗯,请在 Post 模型中尝试has_many :imageposts, inverse_of: :post。看看有没有帮助
【解决方案2】:

您正在传递多个图像。所以你可以使用coocoon gemaccepts_nested_attributes_for

更多信息https://github.com/nathanvda/cocoon

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多