简体   繁体   中英

In Rails, how do I query my database from JavaScript so I can save the value of the query?

I would like to make a query given the id of my book in javascript and not fetch all the books from the database, for example:

I usually do it like this:

In my book controller , I make a query the collection of books and then pass it to the view through a variable:

# books_controllers.rb
before_action :set_books
... 
def set_books
  @books = Book.all # here is my books collection
end

In my form view I define a variable to store the collection of books, in a books_info variable:

#books/form
javascript:
   let books_info = #{@books.to_json.html_safe};

And finally, the collection of books is scanned and compared with the id that the client gives me to find the specific information of said book.

    Array.from(books_info).forEach((element, index) => {
      if (element["book_id"] === client_book_id){
        new_book_id = element;
      }
    });

The problem with doing all that is that I compromise all the book information in views

Simply what I am looking for is given the id of the client ( client_book_id ) to do this in javascript

javascript:
  let client_book_id = #{Book.find(´client_book_id´).to_json.html_safe} # This not work but I try to got it.

If you could help me I would be very grateful.

  1. Add the book ID to the query string of the URL, eg ?book_id=123
  2. The Rails controller reads the ID as eg params[:book_id]
  3. The controller sets an instance variable , eg @book = Book.find(params[:book_id])
  4. The Rails view sets the JS variable using .to_json as already shown in the question

This is just one application design, good for beginners. Other designs include XHR (intermediate) or GraphQL (advanced).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM