Rails-使用has_many保存模型:通过AngularJS层的关联

Rails - Saving a model with has_many :through association from AngularJS layer

本文关键字:AngularJS 通过 关联 模型 has 使用 many 保存 Rails-      更新时间:2023-09-26

我正在制作一个后端带有Rails的Angular JS应用程序。我正在尝试更新与注释关联的标记,但我无法解决。我很确定这与POST请求中表示我的数据的方式有关,它看起来像这样:

Started POST "/lesson_notes/notes" for 127.0.0.1 at 2014-04-29 09:53:04 +1000
Processing by LessonNotes::NotesController#create as HTML
  Parameters: "body"=>"hello", "note_type_id"=>2, "tag_ids"=>[1, 3], "note"=>{"body"=>"hello", "note_type_id"=>2}}

这是Rails中的注释模型:

class Note < ActiveRecord::Base
  has_many :taggings, as: :taggable
  has_many :tags, through: :taggings
end

这是我的Rails中的Notes控制器:

class NotesController < ApplicationController
  def create
    @note = Note.new note_params
    if @note.save
      render json: @note, status: 201
    else
      render json: { errors: @note.errors }, status: 422
    end
  end
  private
  def note_params
    params.require(:note).permit(:body, :note_type_id, :tag_ids)
  end
end

在表单中,我有一个由输入过滤的标签列表。当你点击过滤列表中的标签时,它会将标签添加到targetNote角度模型:

<form name="noteForm" ng-submit="processNote(noteForm.$valid)" novalidate>
  <ul class="list-inline">
    <li ng-repeat="t in targetNote.tags">
      {{t.name}}
    </li>
  </ul>
  <input id="add-tag" type="text" ng-model="tagQuery"></input>
  <ul>
    <li ng-repeat="t in tags | filter:tagQuery">
      <button type="button" class="btn btn-default btn-sm" ng-click="addTag(t)">{{t.name}}</button>
    </li>
  </ul>
  <button type="submit" class="btn btn-primary" ng-disabled="noteForm.$invalid">{{formAction}}</button>
</form>

在我的角度控制器中,以下是相关方法:

LessonNotes.controller("NotesCtrl", ["$scope", "Note", "Tag", "Alert",
  function($scope, Note, Tag, Alert) {

    $scope.targetNote = new Note();
    $scope.tags = Tag.query();
    $scope.processNote = function(isValid) {
      $scope.targetNote.$save(
        function(n, responseHeaders) {
          Alert.add("success", "Note updated successfully!", 5000);
        },
        function(n, responseHeaders) {
          Alert.add("warning", "There was an error saving the note!", 5000);
        }
      );
    };
    $scope.addTag = function(tag) {
      if($scope.targetNote.tags.indexOf(tag) < 0) {
        $scope.targetNote.tags.push(tag);
        if(!("tag_ids" in $scope.targetNote)) {
          $scope.targetNote['tag_ids'] = [];
        }
        $scope.targetNote.tag_ids.push(tag.id);
      }
    };
}]);

我之前的答案是有效的,但最终我得到了一些不同的答案。

在Notes模型的Rails后端,我定义了这个setter:

def tag_list=(names)
  self.tags = names.map do |n|
    ::Tag.where(name: n).first_or_create!
  end
end

这样,我就可以简单地在JSON中发送一个标签名称数组,而不用担心标签是否已经创建。

在控制器中,我定义了我的强参数,比如

def note_params
  params.permit(:body, :note_type_id, {tag_list: []})
end

注意:我的模型是Rails引擎的一部分,但Tag模型是在父级中定义的。这就是为什么我将模型引用为::Tag。通常,仅Tag就足够了。

我最终只是为Tagging创建了一个Angular$资源,并在Note模型成功保存后直接在回调中更新了该表。