我在后端制作了一个带有Rails的Angular JS应用程序。我试图更新标签与笔记相关联,但我无法弄清楚。我敢肯定它是与我的数据在POST请求的表示方式,它看起来像这样:Rails - 通过has_many保存模型:通过来自AngularJS层的关联
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的:
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);
}
};
}]);