Search code examples
ruby-on-railsruby-on-rails-4nested-formsnested-attributes

Implement order pages with rails


I wanna implement a order page, but it's so hard...

The system is in portugues, for others reasons, sorry about this.

My view:

conta/pedidos/index.html.erb

<h3>Meus pedidos</h3>

<table>
  <thead>
    <th>#</th>
    <th>Data do pedido</th>
  </thead>
  <tbody>
    <% @pedidos.each do |pedido| %>
      <tr>
        <td><%= link_to pedido.id, pedido_path(pedido.token) %></td>
        <td><%= pedido.create_at.to_s(:long) %></td>
      </tr>
    <% end %>
  </tbody>
</table>

My controller:

conta/pedidos_controller.rb

class Conta::PedidosController < ApplicationController
  before_action :authenticate_usuario!
  def index
    @pedidos = current_usuario.pedidos.order("id DESC")
  end
end

My model:

pedido.rb

class Pedido < ActiveRecord::Base
  belongs_to :pessoa
  has_many :itens, class_name: "ItemPedido" , dependent: :destroy

  accepts_nested_attributes_for :enderecos

  before_create :gerar_token

  def gerar_token
    self.token = SecureRandom.uuid
  end

end

And the error:

ArgumentError in Conta::PedidosController#index
No association found for name `enderecos'. Has it been defined yet?

Please, what I make?


Solution

  • I'm not sure why do you have accepts_nested_attributes_for :enderecos in pedido.rb. It's not mentioned anywhere in the provided code. Can you simple comment/remove it?

    If it's need, then you need to set association for it: may be has_many :enderecos