小编RTP*_*mad的帖子

Rails 4不通过JSON更新嵌套属性

我已经搜索了相关的问题,但仍然有问题从我的AngularJS前端返回的rails 4到JSON中更新嵌套属性.

问题:下面的代码概述了从我的Rails4应用程序中从AngularJS传递到Candidate模型的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"}]}
Run Code Online (Sandbox Code Playgroud)

然后,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"}}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

candidate.rb模型包含以下代码,用于定义与工作模型的has_many关系:

class Candidate < ActiveRecord::Base

  ## Model Relationships
  belongs_to :users
  has_many :works, :dependent => :destroy  

  ## …
Run Code Online (Sandbox Code Playgroud)

json ruby-on-rails nested-attributes ruby-on-rails-3 ruby-on-rails-4

12
推荐指数
2
解决办法
3190
查看次数