jeudi 9 février 2017

Ruby on Rails - Adding data to model from Javascript

I'm trying to implement a tag/category system using tag-it, but I'm unsure the best method I should be using to pass the data back to the model.

Currently what I'm trying to do is using ajax to call add_tag and pass the tagLabel.

// application.js

$("#tags").tagit({
    beforeTagAdded: function(event, ui) {
        // do something special
        $.ajax({
          url: "add_tag",
          data : {name: ui.tagLabel }
      });
    }
});

And within my controller, I just add the param and save it.

// posts_controller.rb

  def add_tag
    @post.category_list.add( params[:name] )
    @post.save
  end

While this works for existing posts, I can't use this method for new posts.

And it makes my routes.rb file cluttered if I plan to use this method on multiple models.

// routes.rb

get '/posts/:id/add_tag' => 'posts#add_tag', as: :post_add_tag

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire