在尝试访问Order模型的属性时,在Customers#index中没有方法错误

时间:2015-10-01 17:42:25

标签: ruby-on-rails

如何从Customer表访问我的订单操作视图索引中的客户名称。反之亦然。

我收到此错误:

客户#index中的NoMethodError。
#Customer的未定义方法`order':0x24f4 ...

class Customer < ActiveRecord::Base
    has_many :orders, foreign_key: "customer_id"
end

 class Order < ActiveRecord::Base
    belongs_to :customer
end

在我的迁移中:

   create_table "customers", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "orders", force: :cascade do |t|
    t.integer  "customer_id"
    t.datetime "orderdate"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "orders", ["customer_id"], name:     "index_orders_on_customer_id", using: :btree

end

在客户的index.html.erb

<% @customers.each do |customer| %>
      <%= customer.name %>
      <%= customer.order.orderdate %>
<% end %>

在订单的index.html.erb

<% @orders.each do |order| %>
   <%= order.orderdate %>
      <%= order.customer.name %>
<% end %>

2 个答案:

答案 0 :(得分:0)

您与客户和订单有很多关系,所以

在客户的index.html.erb

<% @customers.each do |customer| %>
      <%= customer.name %>
       <!-- this will display customers all order and fetch first and then show that order's orderdate -->
      <%= customer.orders.first.orderdate %>
<% end %>

答案 1 :(得分:0)

尝试使用其他方法在迁移中设置模型之间的关系:

t.belongs_to :customer, index: true

请参阅http://guides.rubyonrails.org/association_basics.html#the-belongs-to-association