[英]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:我想根据我在 javascript 中的图书 ID 进行查询,而不是从数据库中获取所有图书,例如:
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:在我的书 controller中,我查询了书籍的集合,然后通过变量将其传递给视图:
# 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_info变量中定义了一个变量来存储书籍的集合:
#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.最后,对藏书进行扫描,并与客户给我的id进行比对,找到该书的具体信息。
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 中给出了客户端的 ID ( client_book_id ) 来执行此操作
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
?book_id=123
params[:book_id]
params[:book_id]
@book = Book.find(params[:book_id])
@book = Book.find(params[:book_id])
.to_json
as already shown in the question .to_json
设置 JS 变量,如问题中所示This is just one application design, good for beginners.这只是一个应用程序设计,适合初学者。 Other designs include XHR (intermediate) or GraphQL (advanced).
其他设计包括 XHR(中级)或 GraphQL(高级)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.