如何从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 %>
答案 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