Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 你有一次经历过,也有很多次经历过_Ruby On Rails_Ruby On Rails 3_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 你有一次经历过,也有很多次经历过

Ruby on rails 你有一次经历过,也有很多次经历过,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,你好,我有3个型号: 出售 顾客 客户地址 -每笔销售只能有一名客户 -每个客户可以有多个销售 这很好,这里没有问题,但现在我需要这样的东西: -每笔销售只应有一个客户地址 -每个客户可以有多个客户地址 那么,我该怎么做呢 我可以使用has-one-through和has-many-through吗?首先在客户和地址之间创建1-n关联: class Customer < ApplicationRecord has_many :addresses end class Addres

你好,我有3个型号:

  • 出售
  • 顾客
  • 客户地址
-每笔销售只能有一名客户

-每个客户可以有多个销售

这很好,这里没有问题,但现在我需要这样的东西:

-每笔销售只应有一个客户地址

-每个客户可以有多个客户地址


那么,我该怎么做呢


我可以使用has-one-through和has-many-through吗?

首先在客户和地址之间创建1-n关联:

class Customer < ApplicationRecord
  has_many :addresses
end

class Address < ApplicationRecord
  belongs_to :customer
end
class客户
然后添加订单模型并设置关联:

class Customer < ApplicationRecord
  has_many :addresses
  has_many :sales
end

class Address < ApplicationRecord
  belongs_to :customer
  has_many :sales_as_shipping_address, class_name: 'Sale',
                                       foreign_key: 'shipping_address_id'
end

class Sale < ApplicationRecord
  belongs_to :customer
  belongs_to :shipping_address, class_name: 'Address'
end
class客户
这创建了两个独立的关联-销售和客户都有不同的关联要处理

如果您想通过销售加入客户地址,我们可以:

class Customer < ApplicationRecord
  has_many :addresses
  has_many :sales
  has_many :shipping_addresses, through: :sales, 
                               source: :shipping_address
end
class客户
您希望在哪些型号之间建立这种关联?我在这里看不到这种需要..我需要在地址表中创建“发货地址id”?否-
发货地址id
销售
表中
属于_to
将外键放置在models表上。把它放在地址上意味着一个地址可以在一次销售中使用。