Ruby on rails active record associations

本小妞迷上赌 提交于 2019-12-13 09:37:45

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/8771551/ruby-on-rails-active-record-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!