I am playing around with Rails and Angular and trying to get a simple association to update via a JSON PUT request from the frontend.
Association: Article has_many :categories, through: :article_categories
Article model:
class Article < ActiveRecord::Base
validates :title, presence: true, uniqueness: true
validates :body, presence: true
has_many :article_categories
has_many :categories, through: :article_categories
accepts_nested_attributes_for :categories
end
I've got no issues updating the title
and body
, but I cannot update the article's categories.
Here are the relevant controller parts
def update
@article = Article.find(params[:id])
if @article.update(article_params)
render json: @article, status: 200
end
end
private
def article_params
params.require(:article).permit(:title, :body,
categories_attributes: [:name, :id])
end
My incoming JSON looks like this, spaced out to make it more readable:
Started PUT "/api/v1/articles/6" for 127.0.0.1 at 2014-06-01 17:53:04 +0900
Processing by Api::V1::ArticlesController#update as HTML
Parameters: {"title"=>"new title", "body"=>"blablabla", "id"=>"6", "categories"=>
[{"name"=>"Ruby", "id"=>1}, {"name"=>"Javascript", "id"=>2}, {"name"=>"HTML", "id"=>3},
{"name"=>"CSS", "id"=>4}],
"categories_attributes"=>[{"name"=>"Ruby", "id"=>1},
{"name"=>"Javascript", "id"=>2}, {"name"=>"HTML", "id"=>3}, {"name"=>"CSS", "id"=>4}],
"article"=>{"id"=>"6", "title"=>"new title", "body"=>"blablabla"}}
The only feedback I get is that article id
isn't a whitelisted param. Isn't the categories_attributes
what Rails looks for when it takes nested attributes? Why isn't it complaining about the categories
params not being whitelisted?