Question:
Hi, I'm developing an Engine on Rails 5 which will be just a blog API. It will be a simple system. Post has lots of Passions and Passions has lots of Posts. I made the relationship N <->
The problem is that when I send the post's JSON with the IDs of the Passions I want to associate with it, I can't 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 the api '/feed/posts' to be able 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 rails log that receives the request the 'passion_ids' attribute is not sending inside the post so I can allow it.
Log when sending 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 inside 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 on rails 4.2 and entries are made by forms and not by REST.
Answer:
I think there are some questions there. First, I think your JSON request should have a root, in this 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 must allow it differently, like this:
params.require(:post).permit(:title,
:description,
passion_ids: [])
So rails knows you're going to pass an array. Hope this helps.