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.
?book_id=123
params[:book_id]
@book = Book.find(params[:book_id])
.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.