我有问题。我需要知道是否存在某种方式使用以下关联以更简单的方式从一个类导航到另一个类
SCHEMA
ActiveRecord::Schema.define(version: 20140712054858) do
create_table "customers", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "orders", force: true do |t|
t.integer "customer_id"
t.datetime "order_date"
t.datetime "created_at"
t.datetime "updated_at"
end
end
customer.rb
class Customer < ActiveRecord::Base
end
order.rb
class Order < ActiveRecord::Base
belongs_to :customer
end
我的使用方法
2.0.0-p481 :044 > @customer1=Customer.create(:name=>"John")
(0.2ms) begin transaction
SQL (0.6ms) INSERT INTO "customers" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", Sat, 12 Jul 2014 06:18:24 UTC +00:00], ["name", "John"], ["updated_at", Sat, 12 Jul 2014 06:18:24 UTC +00:00]]
(162.3ms) commit transaction
=> #<Customer id: 4, name: "John", created_at: "2014-07-12 06:18:24", updated_at: "2014-07-12 06:18:24">
2.0.0-p481 :045 > @order1=Order.new
=> #<Order id: nil, customer_id: nil, order_date: nil, created_at: nil, updated_at: nil>
2.0.0-p481 :046 > @order1.order_date=Time.now
=> 2014-07-12 03:19:31 -0300
2.0.0-p481 :047 > @order1.customer_id=@customer.id
=> 1
2.0.0-p481 :048 > @order1.save
(0.2ms) begin transaction
SQL (0.7ms) INSERT INTO "orders" ("created_at", "customer_id", "order_date", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sat, 12 Jul 2014 06:20:03 UTC +00:00], ["customer_id", 1], ["order_date", Sat, 12 Jul 2014 06:19:31 UTC +00:00], ["updated_at", Sat, 12 Jul 2014 06:20:03 UTC +00:00]]
(171.1ms) commit transaction
=> true
没有某种方式让@ customer1。@ order1和?自动映射?
答案 0 :(得分:1)
您可以像Customer
这样设置反向关联:
class Customer < ActiveRecord::Base
has_many :orders
end
这样您就可以更轻松地创建Order
记录:
@order1 = @customer1.orders.create(order_date: Time.now)
通过在has_many :orders
中说Customer
,Rails假定Order
表格中有customer_id
,在您的情况下,它是开箱即用的。
答案 1 :(得分:0)
<强>协会强>
您当然需要查看ActiveRecord Associations - belongs_to
需要与has_many
匹配:
所以你的模型看起来像:
#app/models/customer.rb
Class Customer < ActiveRecord::Base
has_many :orders
end
#app/models/order.rb
Class Order < ActiveRecord::Base
belongs_to :customer
end
这一点非常重要 - 当您创建模型的实例时,您基本上实例化了一个Ruby对象。您的对象的attributes
将从表格的列中提取,更重要的是,您可以使用associations
使用has_many
或belongs_to
创建一种方法,将对象附加到当前/父级对象 - 这意味着您可以调用以下内容:
#app/controllers/customers_controller.rb
Class CustomersController < ApplicationController
def show
@customer = Customer.find params[:id]
@orders = @customer.orders
end
end