Many to Many JSON POST - Rails 5 - Only API

3

Hello, I'm developing an Engine in Rails 5 where it will be just a blog API. It will be a simple system. Post has several Passions and Passions has several Posts. I made the N < - >

The problem is that when sending the JSON of the post with Passion IDs that I want to associate with it, I can not save them.

Post.rb

module Feed
  class Post < ApplicationRecord
    has_many :post_passions,  dependent: :destroy 
    has_many :passions, :through => :post_passions
  end
end

Passion.rb

module Feed
  class Passion < ApplicationRecord
    has_many :post_passions
    has_many :post, :through => :post_passions
  end
end

PostPassion.rb (Join Table)

module Feed
  class PostPassion < ApplicationRecord
     belongs_to :passion
     belongs_to :post
  end
end

My goal is through a POST request in api '/ feed / posts' to create a post specifying several Passions. The JSON I am sending is as follows.

{
  "title": "Titulo da postagem",
  "description":"Decrição do post",
  "passion_ids":[1,2]
}

Sending this post when looking at the log of the rails that receives the request the attribute 'passion_ids' is not sending inside post so I can allow it.

Log when submitting the request

Started POST "/feed/posts" for 127.0.0.1 at 2017-03-29 08:20:00 -0300
Processing by Feed::PostsController#create as */*
Parameters: {"title"=>"Titulo da postagem", "description"=>"Decrição do post", "passion_ids"=>[1, 2], "post"=>{"title"=>"Titulo da postagem", "description"=>"Decrição do post"}}

As the 'passion_ids' is not received within Post the permit below does not work.

params.require(:post).permit(:title,
                             :passion_ids,
                             :description)

I have a system that works that way but it's in rails 4.2 and the forms are made by forms and not by REST.

    
asked by anonymous 29.03.2017 / 13:28

3 answers

2

I think there are some issues there. First, I think your JSON request should have a root, in case:

{
    "post": {
        "title": "Titulo da postagem",
        "description":"Decrição do post",
        "passion_ids":[1,2]
    }
}

Second, if you want to pass an array as an attribute, you should allow it differently, like this:

params.require(:post).permit(:title,
                             :description,
                             passion_ids: [])

So rails know you'll pass an array. I hope I have helped.

    
29.03.2017 / 20:51
0

I believe the error is here

params.require(:post).permit(:title,:passion_ids,:description)

your ': passion_ids' is as an attribute of: post, while it is being passed in the root of the parameters by the request.

    
29.03.2017 / 13:38
0

To get passion_ids you need to have this attribute passion_ids in model.post

params.require(:post).permit(:title, :passion_ids, :description)

    
31.03.2017 / 18:41