mardi 30 mai 2017

Rails and ember with acts-as-taggable-on. How to handle relationships in JSONAPI endpoint?

I have a Rails 5 (or 4) application and I need a good tag system.

  • First question: is acts-as-taggable-on still a good choice?

This is my code:

class User < ActiveRecord::Base
  acts_as_taggable_on :tags
end

class UsersController < ApplicationController
  def user_params
    params.require(:user).permit(:name, :tag_list)
  end
end

@user = User.new(:name => "Bobby")

I'm able to add and remove with this (from Rails console or code):

@user.tag_list.add("awesome")
@user.tag_list.remove("awesome")

  • Second question: how can I handle relationship?

I'll explain it better: let's say I'm using Ember (or also Angular or others with JSONAPI, it's the same for my question), and I'm using ActiveModelSerializer 0.10.x:

app/models/user.js:

import DS from 'ember-data';

export default DS.Model.extend({
  tags: DS.hasMany('tag')
});

app/models/tag.js:

import DS from 'ember-data';

export default DS.Model.extend({
  users: DS.hasMany('user')
});

app/routes/myroute.js:

let user = this.get('store').peekRecord('user', 1);
let tag = this.get('store').createRecord('tag', {
  user: user
});
tag.save();

Now I have the problem: how can I say Rails to save this new tag (in taggings table I think)?

Generally when I have a relationships to handle in Ember I create a JSONAPI endpoint in Rails and with foreignKey and CREATE api I save all and it works good. But with acts-as-taggable-on I don't know how to save.

Maybe I have to generate a new endpoint for taggings and write my own code in a controller to handle savings for tags? Really? Maybe i'm missing something...




Aucun commentaire:

Enregistrer un commentaire