0

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...

1
  • Post the received params (See server log) Commented Jul 26, 2017 at 5:52

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

its work but it replied => { "imageposts.post": [ "must exist" ] }. while i has a post_id attributes
Hm, please, try has_many :imageposts, inverse_of: :post in the Post model. Let's see if it helps
0

You are passing multiple images. So you can use coocoon gem with accepts_nested_attributes_for

for more info https://github.com/nathanvda/cocoon

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.