简体   繁体   English

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

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

I'm making an Angular JS app with Rails in the back end. 我正在后端制作一个带有Rails的Angular JS应用程序。 I'm trying to update the tags associated with a note , but I can't figure it out. 我正在尝试更新与笔记相关联的标签 ,但我无法弄明白。 I'm pretty sure it has something to do with the way my data is represented in the POST request, which looks like this: 我很确定它与我在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}}

Here's the Note Model in Rails : 这是Rails中Note模型

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

Here's my Notes Controller in Rails : 这是我在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

In the form I have a list of tags filtered by an input. 在表单中,我有一个由输入过滤的标签列表。 When you click on a tag in the filtered list it adds the tag to the targetNote Angular model: 当您单击筛选列表中的标记时,它会将标记添加到targetNote Angular模型:

<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>

In my Angular controller here are the relevant methods: 在我的Angular控制器中,这里有相关的方法:

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);
      }
    };

}]);

My previous answer worked, but eventually I ended up with something a little different. 我之前的回答有效,但最终我得到了一些不同的东西。

In the Rails back end on my Notes model I defined this setter: 在我的Notes模型的Rails后端,我定义了这个setter:

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

That way I was able to simply send an array of tag names in the JSON without worrying if the tag was already created or not. 这样我就可以简单地在JSON中发送一组标签名称而不必担心标签是否已经创建。

In the controller I defined my strong parameters like so 在控制器中我定义了我的强参数

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

Note : My model is part of a Rails engine, but the Tag model is defined in the parent. 注意 :我的模型是Rails引擎的一部分,但Tag模型在父级中定义。 That's why I'm referencing the model as ::Tag . 这就是我将模型引用为::Tag Normally, just Tag is good enough. 通常,只有Tag足够好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails:通过表单中的对象 ID 数组进行 has_many 关联 - Rails: has_many association through array of object IDs from form Rails form_for has_many通过使用AJAX的关联不起作用 - Rails form_for has_many through association using AJAX not working 从has_many关联中加载Ajax实例 - Ajax load instances from a has_many association Ember和Rails has_many关系 - Ember and Rails has_many relationship Rails通过连接记录通过JavaScript将新的has_many附加到嵌套表单 - Rails append new has_many through join record to nested form via javascript 如何在没有nested_form的情况下将表单写入has_many关联? - How to write form to has_many association without nested_form? Rails:使用has_many关系时,link_to(...,remote:true)的行为不一致 - Rails: Inconsistent behavior with link_to(…, remote: true) when using has_many relationship Rails 6 使用 has_many 关系和 accepts_nested_attributes_for 连接表 - Rails 6 Joins Tables using has_many relationships and accepts_nested_attributes_for Rails嵌套属性form_for for has_many,使用javascript无限制嵌套模型 - Rails Nested Attributes form_for for has_many with unlimited nested models using javascript Rails-创建父级时如何动态创建属于has_many关系的成员? - Rails - How do you create members that are part of a has_many relationship dynamically when creating the parent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM