0

I have an array in my javascript file app/assets/javascript/pages/books_page.js :

var booksPage = Backbone.Model.extend({
  defaults: {
    authors: []
  }
  ...

How can I pass that to my controller as a param. The path of my controller is app/controllers/books_controller.rb ?

I think I might need an ajax request and tried the following but it is not working:

$.ajax({
        type: "post",
        url: "/books_controller",
        data: { list_authors: this.get('authors') },
      });

Specifically, I am not sure what the url needs to be. Your help here will be greatly appreciated. Thanks.

3 Answers 3

1

Backbone (and jQuery) should do all the heavy lifting for you. Set the urlRoot in the model:

var booksPage = Backbone.Model.extend({
  urlRoot: '/books',
  ...
});

and then call save on the instance to send the data to the server:

// Get or create `books` as a `booksPage` instance as usual...
// Then make some changes to `books` using `books.set(...)`...
books.save();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use JSON.stringify, and parse it from Controller JSON.parse(params).

$.ajax({
      type: "post",
      url: "/books_controller",
      data: { list_authors: JSON.stringify(this.get('authors')) }
});

2 Comments

but what about the url ??
@Jadoo I do not know yr urls, just make sure passing right params and getting them right.
0
type: 'POST', 
url: `/books/${this.id}`, // or '/books/' + this.id,
data: {
  _method: 'put'
}

This will route you to the BooksController#update. You also need to merge the _method entry into your data object.

"NOTE: Because submitting forms with HTTP methods other than GET and POST isn't widely supported across browsers, all other HTTP methods are actually sent over POST with the intended method indicated in the _method parameter. Rails automatically detects and compensates for this." - Working with JavaScript in Rails

8 Comments

Why not just go with type: 'put'?
@muistooshort 2.4 How do forms with PATCH, PUT, or DELETE methods work? It's an old work around baked pretty deep into Rails to handle lack of browser support.
@muistooshort It is referenced as far back as at least 10 years ago in the Rails doumentation!
But you're not using a <form>.
@muistooshort shhh, don't let Rails know! "When parsing POSTed data, Rails will take into account the special _method parameter". The _method is used in POST requests, not only form submission. Take, for instance, a remote: true form sending back an AJAX request.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.