Retrieve field with Join in RUBY/Ror view

Asked

Viewed 42 times

1

I have a big doubt, I’m a beginner in Ruby, and I’m not able to print the value of a field in my view, the result is this.

inserir a descrição da imagem aqui

My Model:

    class Pedido < ActiveRecord::Base
      has_many :produtos      

      scope :waiting, -> { where(status: 1) }
end

My Controller:

class Backoffice::PedidosController < BackofficeController

  def index
    @pedidos = Pedido.waiting       
  end

end

And in my View it’s like this:

<tbody>               
  <% @pedidos.each do |pedido| %>
    <tr> 
      <th><%=pedido.id%></th>
      <th><%=pedido.status%></th>
      <th><%=pedido.created_at%></th>
      <th><%=pedido.produtos.select(:valor) %></th>
     </tr>
   <% end %>
 </tbody>

I have tried several ways and always print what is in the print, if I change the line to

<%=product request.product. %>

error on the page.

Someone can give me a light?

1 answer

0


Try to specify which Produto of the association, for example:

<%= pedido.produtos.first.valor %> In this case, returns the first Produto of the association.

I don’t know how it will be implemented, but finally, how Pedido has many Produtos, when you search for this association, returns a collection of Produtos, and you need to specify which one you want.

Or if you want to add up the value of Produtos:

<%= pedido.produtos.sum(:valor) %>

  • Thank you very much, I thought exactly that, I just didn’t know how to do it. Now I have to think of a way to present all Products linked to the Order, but for that I will have to change my view. Do you have any idea how I’ll need to implement this? Will I have to go through an array? Thank you very much.

  • I found the command <%= request.products.Pluck (:value) %> which presents the values in my view in the form of an array, this already gives me a light, I have to think of a logic to later present this data in another screen of better reading for the user.... Thanks

  • Yes, this way you are doing, you will have to go through the products to show all the products (ordering.productos.each). If you haven’t done it yet, I would make a new Controller (Products), to show the Order Products on another page, so it would be more organized your views. Take a look at nested Routes, this can help you get a better idea of Rails for these cases (http://guides.rubyonrails.org/routing.html#nested-Resources)

  • I’ll do it, thank you very much Luis!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.