Search code examples
ruby-on-railsrubyactiverecordactive-model-serializers

rails strong parameter error on array attribute


i try to post my json to rails server with this request body

    {"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

  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

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

i've trying this to my imageposts strong parameter but it doesnt work too

imageposts: [:imageurl]

can anybody solve this...


Solution

  • The strong params are fine. 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)

    If you want it to be updated like this, the possible solution is to use 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:

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