【问题标题】:updating associated model in rails更新 Rails 中的关联模型
【发布时间】:2016-02-07 00:18:07
【问题描述】:

我很困惑如何最好地从带有角度前端的 rails 中的关联模型更新数据(尽管这实际上更像是一个 rails 问题)。

假设我有一个名为 votable 的模型,其中包含一些属性(start_date、end_Date)和 has_many 文本(不同语言的 votable 描述)

class Votable < ActiveRecord::Base
  has_many :votable_texts
  accepts_nested_attributes_for :votable_texts
end

我的控制器中的 show 方法生成 json 数据,我在 Angular 中使用这些数据来构建表单:

def show
  respond_to do |format|
    format.json { 
      render :json => @votable.to_json(
        :except => [:created_at, :updated_at],
        :include => {
          :votable_texts => { 
            :except => [:created_at, :updated_at]
          }
        } 
      ) 
    }
  end
end

这会生成类似于以下 json 的内容:

{
  "id": 2,
  "start_date": "2015-02-05T00:00:00.000Z",
  "end_date": "2016-02-02T00:00:00.000Z",
  "votable_texts": [
    {
      "id": 6,
      "votable_id": 2,
      "locale": "nl",
      "issue": "Test"
    },
    {
      "id": 2,
      "votable_id": 2,
      "locale": "en",
      "issue": "Test"
    }
  ]
}

在角度方面,我将此 json 读入一个变量并使用 ng-model 将此数据绑定到我的表单。当用户点击保存按钮时,我使用 $http.put 将此数据发布回 rails(与 rails 生成的 json 结构相同)。

问题是 votable 模型的属性确实会更新(例如 start_date),但嵌套 votable_texts 模型中的属性不会更新。

控制器的相关部分如下所示:

def update
  respond_to do |format|
    if @votable.update(votable_params)
      format.json { render :show, status: :ok, location: @votable }
    else
      format.json { render json: @votable.errors, status: :unprocessable_entity }
    end
  end
end

private 

def votable_params
  params.permit(:id, :start_date, :end_date, :votable_texts)
end

我错过了什么?我是否需要自己手动处理关联的更新?如何做到最好?

谢谢!

【问题讨论】:

    标签: ruby-on-rails angularjs


    【解决方案1】:

    我认为您的问题是因为您需要允许 votable_texts 模型的嵌套参数。然而,当使用 accepts_nested_attributes_forupdate 时,Rails 会期望您通过 voteable_texts_attributes 以更新相关记录。在这种情况下,您将拥有以下内容。

    params.permit(:id, :start_date, :end_date, votable_texts_attributes: [:id, :voteable_id, :locale, :issue])

    因此,您可能需要更新 show 操作以使用 voteable_texts_attributes,否则您将不得不沿线路某处更改参数键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多