niftygrifty
niftygrifty

Reputation: 3652

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

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:

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

Here's my Notes Controller in 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

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:

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

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

}]);

Upvotes: 3

Views: 827

Answers (2)

niftygrifty
niftygrifty

Reputation: 3652

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:

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.

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. That's why I'm referencing the model as ::Tag. Normally, just Tag is good enough.

Upvotes: 1

niftygrifty
niftygrifty

Reputation: 3652

I ended up just creating an Angular $resource for Tagging and updated that table directly in a callback when the Note model was saved successfully.

Upvotes: 0

Related Questions