Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

you can use a loop to get all the value from @books

@books.each do |book|
  <%= book.name %>
  <%= book.price %>
end

doing

@metod = Book.find_by_price("50")

@metod is an instance variable, to access it, you can do @metod.price

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top