2014-07-12 112 views
1

我遇到了問題。我需要的,如果存在一些使用方式如下關聯導航從一類到另一個更簡單的方法Ruby on Rails的Active Record中的belongs_to協會4

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 > @[email protected] 
=> 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和and map自動?

回答

1

您可以從Customer建立反向關聯是這樣的:

class Customer < ActiveRecord::Base 
    has_many :orders 
end 

所以,你可以更輕鬆地創建一個Order記錄:

@order1 = @customer1.orders.create(order_date: Time.now) 

通過並稱Customerhas_many :orders,Rails的假設Order表有一個customer_id,在你的情況下,它是開箱即用的。

0

協會

你肯定會需要仰望你的ActiveRecord Associations - 您belongs_to需要由has_many匹配:

enter image description here

所以你的車型將是這樣的:

#app/models/customer.rb 
Class Customer < ActiveRecord::Base 
    has_many :orders 
end 

#app/models/order.rb 
Class Order < ActiveRecord::Base 
    belongs_to :customer 
end 

T他的理由非常重要 - 當你創建一個模型的實例時,你基本上實例化一個Ruby對象。你的對象的attributes將從您的表中的列繪製,而且,更重要的是,你可以通過使用associations

使用has_manybelongs_to集成更多的對象/關聯數據創建其追加對象的方法您目前的/父母之一 - 意味着您可以撥打以下電話:

#app/controllers/customers_controller.rb 
Class CustomersController < ApplicationController 
    def show 
     @customer = Customer.find params[:id] 
     @orders = @customer.orders 
    end 
end