【发布时间】:2014-06-01 09:07:39
【问题描述】:
我正在使用 Rails 和 Angular,并尝试通过来自前端的 JSON PUT 请求获得一个简单的关联来更新。
协会:Article has_many :categories, through: :article_categories
文章型号:
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
更新title 和body 没有问题,但我无法更新文章的类别。
这里是相关的控制器部分
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
我传入的 JSON 看起来像这样,间隔开以使其更具可读性:
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"}}
我得到的唯一反馈是 article id 不是白名单参数。 categories_attributes 不是 Rails 在使用嵌套属性时所寻找的吗?为什么它不抱怨 categories 参数没有被列入白名单?
【问题讨论】:
-
尝试使用
update_attributes而不是update。此外,如果您使用带有 bang(!) 的update_attributes,它会显示验证错误,例如update_attributes!。 Difference between update and update_attributes
标签: ruby-on-rails json