Ruby on rails 如何在RubyonRails模型之间建立连接?

Ruby on rails 如何在RubyonRails模型之间建立连接?,ruby-on-rails,model,migration,relationship,Ruby On Rails,Model,Migration,Relationship,我需要在Ruby on Rails中建立连接,在数据库中,一个模型引用另一个模型(类似于交换机),它如下所示: 我相信这是一种多态性的联系,但除此之外几乎没有 请给我指出正确的方向。您可以使用类似于“属于”的链接,在每个模型中都有许多链接,以参考它们之间的关系 class Concentrator < ActiveRecord::Base attr_accessible :battery_voltage, :device_id belongs_to :project end 类

我需要在Ruby on Rails中建立连接,在数据库中,一个模型引用另一个模型(类似于交换机),它如下所示:

我相信这是一种多态性的联系,但除此之外几乎没有


请给我指出正确的方向。

您可以使用类似于“属于”的链接,在每个模型中都有许多链接,以参考它们之间的关系

class Concentrator < ActiveRecord::Base
  attr_accessible :battery_voltage, :device_id
  belongs_to :project
end
类集中器
“所属对象”后面的名称是另一个不带s的表名或控制器名 其他关系链接包括:

属于,, 有一个, 有很多,, 有很多:通过, 有一个:通过, 有很多人,有很多人

你可以参考这个


根据您的数据库结构,我对这个问题的解决方案如下:

迁移

# db / schema.rb 
       create_table "switchs", force: true do | t | 
         # t.references :switch, polymorphic: true - in the migration 
         # t.references :item - migration 
         t.integer "switch_id" 
         t.string "switch_type" 
         t.integer "item_id" 
       end 
    
       create_table "options", force: true do | t | 
         t.string "title" 
         ... 
       end 
       create_table "items", force: true do | t | 
          t.string "name" 
          ... 
       end 
# app / models / switch.rb 
       class Switch <ActiveRecord :: Base 
         belongs_to :item 
         belongs_to :switch, polymorphic: true 
         ... 
       end 
相应地,模型本身将立即切换2种通信类型:多态性:和通过

# db / schema.rb 
       create_table "switchs", force: true do | t | 
         # t.references :switch, polymorphic: true - in the migration 
         # t.references :item - migration 
         t.integer "switch_id" 
         t.string "switch_type" 
         t.integer "item_id" 
       end 
    
       create_table "options", force: true do | t | 
         t.string "title" 
         ... 
       end 
       create_table "items", force: true do | t | 
          t.string "name" 
          ... 
       end 
# app / models / switch.rb 
       class Switch <ActiveRecord :: Base 
         belongs_to :item 
         belongs_to :switch, polymorphic: true 
         ... 
       end 

欢迎来到堆栈溢出!不幸的是,堆栈溢出不是解决此问题的合适位置。我们不会为您编写代码。根据,您应该展示您已经尝试过的内容,并在改进代码或填补空白方面寻求帮助。您需要自己编写代码,如果您不确定某些东西为什么不能按预期工作,请在发布代码时解释您希望它做什么,以及它实际在做什么,包括所有错误消息。否则,我无法制作出标准的导轨,一切都是紧凑而美丽的。是的,您可以通过:relation\u项为每个选项使用has\u many*option*,然后我将必须创建另外两个时间表。。。但也许有什么方法可以让garazdo变短?