I have a database and I want to select data from it by pressing a button.
Run $ rails c
1.9.2p290 :001 >Book.find_by_price("50")
# => #<Book id: 1, price: "50"><Book id: 2, price: "50"><Book id: 3, price: "50">
In the console, he finds the right information, but how to show it in the view?
I tried to write a method in the controller.
books_controller.rb
class BooksController < ApplicationController
def index
@books = Book.all
@metod = Book.find_by_price("50")
end
#...
end
And then, in the view
view/books/index.html.erb
<%= link_to @metod %>
But it does not work. Please tell me how is it done?
I would want that these data are displayed when I click the button in the view.
If you are using the dynamic finders of ActiveRecord, find_by_price
should return a single record. But in the console output, it is returning an array so I'm assuming that you manually created that method in your Book model. If the intended output is to list all books with a price of 50, use the following code in your view.
<% @metod.each do |book| %>
<%= link_to book, book %>
<% end %>
This code loops through each book in @metod
and displays a link that goes to the show
action of its corresponding controller.