【发布时间】:2013-11-03 16:07:22
【问题描述】:
我已经搜索了相关问题,但通过从我的 AngularJS 前端返回的 JSON 更新 rails 4 中的嵌套属性仍然存在问题。
问题:下面的代码概述了从 AngularJS 传递到我的 Rails4 应用程序中的候选模型的 JSON。 Candidate 模型有很多 Works,我正在尝试通过 Candidate 模型更新 Works 模型。由于某种原因,Works 模型无法更新,我希望有人能指出我所缺少的。感谢您的帮助。
这是候选人的 AngularJS 前端中的 json:
{"id"=>"13", "nickname"=>"New Candidate", "works_attributes"=>[
{"title"=>"Financial Analyst", "description"=>"I did things"},
{"title"=>"Accountant", "description"=>"I did more things"}]}
Rails 然后通过添加候选标头将此 JSON 转换为以下内容,但不包括候选标头下的嵌套属性,并且无法通过候选模型更新works_attributes:
{"id"=>"13", "nickname"=>"New Candidate", "works_attributes"=>[
{"title"=>"Financial Analyst", "description"=>"I did things"},
{"title"=>"Accountant", "description"=>"I did more things"}],
"candidate"=>{"id"=>"13", "nickname"=>"New Candidate"}}
candidate_controller.rb 包含一个简单的更新:
class CandidatesController < ApplicationController
before_filter :authenticate_user!
respond_to :json
def update
respond_with Candidate.update(params[:id], candidate_params)
end
private
def candidate_params
params.require(:candidate).permit(:nickname,
works_attributes: [:id, :title, :description])
end
end
candidate.rb 模型包含以下代码,定义了与 works 模型的 has_many 关系:
class Candidate < ActiveRecord::Base
## Model Relationships
belongs_to :users
has_many :works, :dependent => :destroy
## Nested model attributes
accepts_nested_attributes_for :works, allow_destroy: true
## Validations
validates_presence_of :nickname
validates_uniqueness_of :user_id
end
最后,works.rb 模型定义了 has_many 关系的另一端:
class Work < ActiveRecord::Base
belongs_to :candidate
end
感谢您提供的任何帮助,因为我确信我遗漏了一些相当简单的东西。
谢谢!
【问题讨论】:
-
Rails then translates this JSON into the following by adding the candidate header什么?你确定Rails会这样做吗?更改客户端应用程序的有效负载不是 Rails 的工作! -
我相当有信心 Rails ActionController::ParamsWrapper 从没有根元素的 Angularjs 获取 json 输入并添加具有根元素的片段。我想我的问题是:这是否会导致问题以及为什么works_attributes 数组未包含在此参数包装更改中?
-
请告诉我你认为这样做的代码。
-
phoet - 感谢您的提问,因为它为我指出了一个解决方案(发布在下面)。如果有更好的方法来管理 AngularJS 和 Rails 之间的 JSON 交互,请告诉我。
-
不确定它是否“更好”——我有点喜欢在服务器而不是客户端处理它的想法——但你可以在 Angular 中添加一个请求拦截器并将请求包装在那里。拦截器的文档在这里:docs.angularjs.org/api/ng/service/$http
标签: ruby-on-rails json ruby-on-rails-3 ruby-on-rails-4 nested-attributes