has_and_belongs_to_many模型创建需要的? [英] has_and_belongs_to_many model creation needed?
问题描述
我的订单和项目表。我也有一个第三个表称为orders_items。我学会了从下面的链接(第2图) HTTP创建:// www.tutorialspoint.com/ruby-on-rails/rails-models.htm
型号/ order.rb
类订单<的ActiveRecord :: Base的
has_and_belongs_to_many:项目,通过:item_order
结束
型号/ item.rb的
类项目<的ActiveRecord :: Base的
has_and_belongs_to_many:订单,通过:item_order
结束
[orders_items]表中有以下内容:
整数:ORDER_ID
整数:ITEM_ID
我一定要建立一个模型/ order_item.rb文件中加入:
belongs_to的:为了
belongs_to的:项目
如果这样什么是正确的命名格式,它应该是什么? 将为模型文件名[order_item.rb]正确区分它指的是哪个表?
型号/ order_item.rb ??
类OrdersItem ??? <的ActiveRecord :: Base的
belongs_to的:订单
belongs_to的:项目
结束
在的 API
连接表不应该有一个主键或相关模型 用它。您必须手动生成连接表迁移 如本
类CreateDevelopersProjectsJoinTable< ActiveRecord的::迁移
高清变化
CREATE_TABLE:developers_projects,ID:假做| T |
t.integer:developer_id
t.integer:PROJECT_ID
结束
结束
结束
指定与另一个类多对一对多的关系。本 联营两班通过中间连接表。除非加盟 表被明确地指定为选项,它是使用猜 的类名词法顺序。因此,开发者之间的连接 项目将为默认加盟developers_projects的表名 因为DprecedesP字母
在你的情况下,连接表的名称应为 items_orders
。
I have orders and items table. I also have a third table called orders_items. Which I learned on creating from the following link (2nd graph) http://www.tutorialspoint.com/ruby-on-rails/rails-models.htm
models/order.rb
class Order < ActiveRecord::Base
has_and_belongs_to_many :items, through: :item_order
end
models/item.rb
class Item < ActiveRecord::Base
has_and_belongs_to_many :orders, through: :item_order
end
[orders_items] table has the following:
integer :order_id
integer :item_id
Do I have to create a models/order_item.rb file to add:
belongs_to :order
belongs_to :item
If so what is the correct naming format that it should be? Would the name for the model file [order_item.rb] correct to distinguish which table it refers to?
models/order_item.rb ??
class OrdersItem ??? < ActiveRecord::Base
belongs_to :order
belongs_to :item
end
From the API
The join table should not have a primary key or a model associated with it. You must manually generate the join table with a migration such as this
class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
def change
create_table :developers_projects, id: false do |t|
t.integer :developer_id
t.integer :project_id
end
end
end
Specifies a many-to-many relationship with another class. This associates two classes via an intermediate join table. Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically
In your case the join table name should be items_orders
.
这篇关于has_and_belongs_to_many模型创建需要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!