Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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
Activerecord _和_是否属于需要创建的许多模型?_Activerecord_Ruby On Rails 4 - Fatal编程技术网

Activerecord _和_是否属于需要创建的许多模型?

Activerecord _和_是否属于需要创建的许多模型?,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我有订单和项目表。我还有第三个表叫orders\u items。这是我从下面的链接(第二张图)中了解到的 models/order.rb class Order < ActiveRecord::Base has_and_belongs_to_many :items, through: :item_order end 我是否必须创建一个models/order_item.rb文件来添加: belongs_to :order belongs_to :item 如果是,那么正确的命名格式应

我有订单和项目表。我还有第三个表叫orders\u items。这是我从下面的链接(第二张图)中了解到的

models/order.rb

class Order < ActiveRecord::Base
 has_and_belongs_to_many :items, through: :item_order
end
我是否必须创建一个models/order_item.rb文件来添加:

belongs_to :order
belongs_to :item
如果是,那么正确的命名格式应该是什么? 模型文件[order_item.rb]的名称是否正确,以区分它引用的表

型号/订单\项目.rb

class OrdersItem ??? < ActiveRecord::Base
 belongs_to :order
 belongs_to :item
end
classordersitem???
您的型号必须命名为OrderItem。你不需要在这个班上。文件名(order_item.rb)正确

我认为你需要这种关系来满足你的需求,除非订单也是一个项目

class Order < ActiveRecord::Base
  has_many :items
end
类顺序

class项
来自

联接表不应具有主键或关联的模型 用它。必须通过迁移手动生成联接表 像这样

class CreatedeveloperProjectsJointable
指定与其他类的多对多关系。这 通过中间联接表关联两个类。除非加入 表被显式指定为选项,使用 类名的词法顺序。因此,开发人员和 Project将提供默认的联接表名称“developers\u projects” 因为按字母顺序“D”在“P”之前


在您的例子中,联接表的名称应该是
items\u orders

,这样我就不需要第三个表OrderItem了?我的订单会有很多项目,而像wise项目一样,它们也有很多订单,不是吗?我可能会感到困惑。这个答案无效。HABTM联接表不应该有型号名称。谢谢,我是根据@Pavan的回答计算出来的,因为一个订单有很多项目,而一个项目有很多订单。我是否在has_和_-allown_-to_-many:[表]之后通过::ordersitems添加您的关联不正确
有且属于许多
不会有通过
选项的
。@Pavan,是的,因为如您所述,连接表不需要任何型号。我明白了,按字母顺序排列!因此,我将删除orders\u items表,转而创建items\u orders。据我所知,我不需要模型/item_order.rb?@lightbots是的,连接表不需要模型,不应该创建。
class OrdersItem ??? < ActiveRecord::Base
 belongs_to :order
 belongs_to :item
end
class Order < ActiveRecord::Base
  has_many :items
end
class Item < ActiveRecord::Base
    belongs_to :order
end
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