Ruby on Rails的活动记录关联 [英] Ruby on rails active record associations

查看:614
本文介绍了Ruby on Rails的活动记录关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要2个型号为我的商店:

  1. ShoeSize

据我的概念 - 一只鞋子可以有多种尺寸(鞋子一个模型可以是34,35,36,37尺寸)

我应该使用什么类型的关联?什么数据库表个行业,我需要创建以支持这些关联?

下面是模型的一个例子中使用:

  Shoe.find(1).shoe_sizes => 34,35,36

ShoeSize(2).shoes => #Shoe1,#Shoe2,#Shoe5
 

解决方案

您应该使用 has_​​and_belongs_to_many 的关系。

 类鞋
  has_and_belongs_to_many:shoe_sizes
结束

类ShoeSize
  has_and_belongs_to_many:鞋
结束
 

这是因为一个鞋可以有很多的鞋的尺寸,并同样一只鞋大小是对于不同的鞋可用

I need 2 models for my store:

  1. Shoe
  2. ShoeSize

According to my concept - one shoe can have several sizes (one model of shoes can be 34,35,36,37 size).

What types of associations should I use? What database table fileds do I need to create to support these associations?

Here is an example of the models in use:

Shoe.find(1).shoe_sizes => 34,35,36

ShoeSize(2).shoes => #Shoe1, #Shoe2, #Shoe5

解决方案

You should use a has_and_belongs_to_many relationship.

class Shoe
  has_and_belongs_to_many :shoe_sizes
end

class ShoeSize
  has_and_belongs_to_many :shoes
end

This is because a Shoe can have many shoe sizes, and likewise one shoe size is available in for different shoes.

这篇关于Ruby on Rails的活动记录关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆