2014-04-28 63 views
3

我在后端制作了一个带有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); 
     } 
    }; 

}]); 

回答

1

我以前的答案有效,但最终我得出了一些与众不同的结论。

在Rails的后端上我的笔记模型我定义这个二传手:

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就够了。

0

我最终只是为标记创建一个Angular $资源,并在注释模型成功保存时直接在回调中更新该表。

相关问题