通过rubyonrails中的脚手架设置对表的引用

Nit*_*ths 18 ruby ruby-on-rails

我现在正在铁轨上做红宝石项目.我创建了一个名为product的实体,我想设置与其他实体命名类别的多对多关系.

script/generate scaffold product prd_name:string category:references 
Run Code Online (Sandbox Code Playgroud)

通过这个代码,只有一对一的映射是可能的.如何在没有硬编码的情况下设置多对多?

noo*_*odl 24

您不应该期望能够通过脚手架单独生成您的应用程序.它仅用于提供入门示例.

在rails中最灵活的多对多关系被称为有很多通过.这需要一个连接表,在这种情况下通常称为"分类".它需要一个product_id声明为belongs to :productcategory_id列和一个声明为的列belongs_to :category.因此将声明三个模型(包括连接模型):

# Table name: products
# Columns:
#   name:string

class Product < ActiveRecord::Base
  has_many :categorisations, dependent: :destroy
  has_many :categories, through: :categorisations
end

# Table name: categories
# Columns:
#   name:string

class Category < ActiveRecord::Base
  has_many :categorisations, dependent: :destroy
  has_many :products, through: :categorisations
end

# Table name: categorisations
# Columns:
#   product_id:integer
#   category_id:integer

class Categorisation < ActiveRecord::Base
  belongs_to :product
  belongs_to :category
end
Run Code Online (Sandbox Code Playgroud)

请注意,我已经命名了列name而不是prd_name因为这是人类可读的并且避免了表名的冗余重复.使用rails时强烈建议这样做.

模型可以像这样生成:

rails generate model product name
rails generate model category name
rails generate model categorisation product:references category:references
Run Code Online (Sandbox Code Playgroud)

作为产生的脚手架,你可以更换modelscaffold前两个指令.尽管如此,除了作为一种学习示例的方法之外,我不推荐它.


Rui*_*tro 14

可以使用这样的命令生成带引用的模型

$ rails generate model Comment commenter:string body:text post:references
Run Code Online (Sandbox Code Playgroud)

请参阅http://guides.rubyonrails.org/getting_started.html#generating-a-model


use*_*754 5

现在可以生成一个带有类似命令的引用的脚手架

$ rails generate scaffold Comment commenter:string body:text post:references
Run Code Online (Sandbox Code Playgroud)


Nit*_*ths -3

我们不能通过脚手架来做到这一点。我们必须编辑类的模型来设置多对多关系。

  • 这不再是真的,请参阅鲁伊·卡斯特罗的回答。 (9认同)