Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.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/5/ruby/23.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 通过rubyonrails中的脚手架设置对表的引用_Ruby On Rails_Ruby - Fatal编程技术网

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

Ruby on rails 通过rubyonrails中的脚手架设置对表的引用,ruby-on-rails,ruby,Ruby On Rails,Ruby,我现在正在做一个关于RubyonRails的项目。我创建了一个名为product的实体,我想设置与其他名为category的实体的多对多关系 script/generate scaffold product prd_name:string category:references 通过编写此代码,只能实现一对一的映射。如何在没有硬编码的情况下设置多对多?您不应该期望能够单独通过脚手架生成应用程序。这只是为了提供一个开始的例子 rails中最灵活的多对多关系称为。这需要一个联接表,在本例中通常称

我现在正在做一个关于RubyonRails的项目。我创建了一个名为product的实体,我想设置与其他名为category的实体的多对多关系

script/generate scaffold product prd_name:string category:references 

通过编写此代码,只能实现一对一的映射。如何在没有硬编码的情况下设置多对多?

您不应该期望能够单独通过脚手架生成应用程序。这只是为了提供一个开始的例子

rails中最灵活的多对多关系称为。这需要一个联接表,在本例中通常称为“分类”。它需要一个
product\u id
列声明为
所属:product
和一个
category\u id
列声明为
所属: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

至于生成脚手架,您可以在前两个命令中将
model
替换为
scaffold
。尽管如此,我还是不推荐它,除非是作为一种学习示例的方式。

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

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

$ rails generate model Comment commenter:string body:text post:references
$ rails generate scaffold Comment commenter:string body:text post:references

请参见

现在可以使用如下命令生成带有引用的脚手架

$ rails generate model Comment commenter:string body:text post:references
$ rails generate scaffold Comment commenter:string body:text post:references

迁移文件呢?这不再是真的,见鲁伊·卡斯特罗的回答。