Ruby on Rails, problem with database when displaying

0

I want to show the data of my rails database on the page.

I have managed to show the entire database, all the information. But what I want is, that only one column appears, in this case the name information. Let me make a list of the names I have in the BD.

In the Index of my controller:

< @f.each do |f| %>
    <%= Terminal.all
<% end %>

On the same controller:

def index
    @f = Terminal.all
end
    
asked by Iker 09.05.2017 в 12:56
source

2 answers

4

Médoto 1: Accessing the desired field in each record

If in your controller you are assigning @f all the records you want to display

#/app/controllers/terminals_controller.rb    
@f = Terminal.all

Then to show a single field, in this case name, you must iterate over all the records that the variable @f has with the method .each and for each record show the field of interest:

#/app/views/terminals/index.html.erb
<% @f.each do |f| %>
  <%= f.nombre %><br>
<% end %>

Medoto 2: Using pluck

In Rails 3.2 or higher, another way would be using .pluck , which would only load the column that you indicate

#/app/controllers/terminals_controller.rb
@f2 = Human.pluck(:name)

And to show in the view it would be something like this:

#/app/views/terminals/index.html.erb
<% @f2.each do |f| %>
  <%= f %><br>
<% end %>

Here is the link for the documentation of pluck .

    
answered by 09.05.2017 / 14:48
source
0

First of all according to the code you published, there are some syntax errors, I will correct them before giving you possible solutions to those that you ask for.

First:

<% @f.each do |f| %> <%= Terminal.all %> <% end %>

Second: if you already defined in the controller that @f= Terminal.all should not repeat it in the view, therefore it would be

<% @f.each do |f| %> <%= f %> <% end %>

Turning to the solution of the problem, you could achieve it in 2 ways

  • On the controller:

    def index @f = Terminal.all.select(:name) end

    In the view:

    <% @f.each do |f| %> <%= f %> <% end %>

  • On the controller:

    def index @f = Terminal.all end

    In the view:

    <% @f.each do |f| %> <%= f %> <% end %>

  • Annotation: I give you an answer based on the code you published, as there are better ways to structure the application, according to the MVC architecture.

        
    answered by 09.05.2017 в 14:52