Rails 问一个 ruby 模型中关系数据库的问题。

so_zengtao · 2014年05月19日 · 最后由 5swords 回复于 2014年05月19日 · 2633 次阅读

1:表 products 有属性:product_detail_id 和 product_type_id 也就是说每个产品都有一个 产品详情 和一个 产品种类

(所以还有表格 ProductDetails 和 ProductTypes) 2:看模型的定义:

下面代码是说 一个 product 实例有一个 (成员变量 C++ 的说法)product_type 类型是 ProductType 通过 :product_type_id 这个值在 ProductTypes 这个表中唯一确定取回该值赋给 product_type (如果理解错了 还望诸位指正)

class Product < ActiveRecord::Base
  validates :product_type_id, presence: true
  validates :product_detail_id, presence: true

  has_one :product_type, foreign_key: :product_type_id, class_name: "ProductType"
  has_one :product_detail, foreign_key: :product_detail_id, class_name: "ProductDetail"

end

我在 ProductType 的模型里面直接这么写不知道可不可以?(可以的话能告诉我为什么嘛?我这里就在 activeadmin 这个 gem 里注册的时候出错了。(是不是要在 ProductTypes 的数据库中加入 product_id 这个列才行?为什么?)

class ProductType < ActiveRecord::Base  
  belongs_to :product
end

1 楼 已删除

你将 product_type_id 和 product_detail_id 放在了 products 表中,所以你需要定义 belongs_to : product_type 和 belongs_to :product_detail 而不是 has_one. 然后在 ProductType 和 ProductDetail 的代码中加上 has_one :product

#1 楼 @saiga 不是很明白你的意思。你的意思就是说 ProductTypes 这个表 有一列叫做 prodcut_id 然后我就 has_one :product_type, foreign_key: :product_id, class_name: "ProductType" 是这个意思么

#3 楼 @so_zengtao 我还是把 1 楼删掉免得误导楼主了= =

楼主定义的应该是 product 属于 type,detail 属于 product。

而外键是定义在从属的那张表,也就是 product 表里面的 product_type_id 和 product_detail 里的 product_id。

所以应该是

class Product < ActiveRecord::Base
  validates :product_type_id, presence: true

  belongs_to :product_type, foreign_key: :product_type_id, class_name: "ProductType"
  has_one :product_detail, foreign_key: :product_id, class_name: "ProductDetail"

end

#2 楼 @qichunren 你的意思说如果我把 product_type_id 和 product_detail_id 放在了 products 表放在了 Products 这个表中 这里必须这样理解:某个商品属于某个类型 某个商品属于某个详情么?但是我想表达的意思是 一个商品有一个类型 一个商品有一个详情 那么我是不是应该在 producttypes 里面加入 prodcut_id 这个列(因为我想通过某个商品来确定他的类型和详情 其实意思一样的 这样冲突么、)

#4 楼 @saiga 你这样说我就很清楚的。。。(容我在想想)

既然都只有一个,has_one, 干嘛费事弄两个新表,全放一个表里面不就得了

#6 楼 @so_zengtao belongs_to 的 foreign_key 是在当前表的。这个用 一对多来解释比较清晰

class Event < ActiveRecord::Base
    has_many :attendees # 複數
    #...
end

class Attendee < ActiveRecord::Base
    belongs_to :event # 單數
end

以上图和代码来自 rails 实战圣经

我是根据你的表定义来的,就是说如果表中有 xxx_id,那么它必然是 belongs_to :xxxs 的,而不是 has_one 这样的。

根据你的需求,#4 楼 @saiga 是对的。

#8 楼 @saiga 多谢耐心的指导。我想我应该明白了^_^

#9 楼 @qichunren 多谢 2 位的耐心回复 我已经明白了 多谢了

#9 楼 @qichunren 原来你是黄冈人啊 - - 武汉人在上海的 +1 - - 刚开始入手 rails.

#7 楼 @billy 是的,特别是这两个外键(子表)还必须存在。我感觉 type 肯定不会是 1 对 1 的。这所以这儿 type 应该是 belongs_to,另一边 type 是 has_many 的,detail 干脆并进来。如果 detail 不是必须存在的,那这儿 has_one,在 detail 里 belongs_to 还可以说得过去。

#14 楼 @5sword 这样是为了简化逻辑 反正也是练习 咱们没有注意那么多

#7 楼 @billy 就是想理解这个东西 学习 而不是做产品。想知道为什么这么弄

#16 楼 @so_zengtao 关于用法的话看 rails guides 就可以了,但实际上 1 对 1 的外键放哪边,分不分表等等,有时候真是很纠结。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号