2014-07-12 82 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