Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.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 Rails-属于模型,其中模型可以是实现关系的任何模型?_Ruby On Rails_Activerecord_Associations_Rails Activerecord - Fatal编程技术网

Ruby on rails Rails-属于模型,其中模型可以是实现关系的任何模型?

Ruby on rails Rails-属于模型,其中模型可以是实现关系的任何模型?,ruby-on-rails,activerecord,associations,rails-activerecord,Ruby On Rails,Activerecord,Associations,Rails Activerecord,可以在Rails 3中实现关联吗 class ApiCredentials < ActiveRecord::Base belongs_to Model end 类ApiCredentials

可以在Rails 3中实现关联吗

class ApiCredentials < ActiveRecord::Base
  belongs_to Model

end
类ApiCredentials 其中,
模型
可以是任何模型

然后在
api\u凭证
表中,我有
model\u id
model
等字段来跟踪此关联

我不认为方便的标准ActiveRecord查询仍然有效,但是有没有人有效地实现了这样的功能,或者使用了其他方法

最后,我想做的只是检查一个特定的模型是否有
ApiCredentials
,但我无法事先知道该模型是否会实现它


提前谢谢

听起来你在谈论一个:

对于多态关联,一个模型可以在单个关联上属于多个其他模型。例如,您可能拥有属于员工模型或产品模型的图片模型。
[…]
您可以将多态的
属于
声明视为设置任何其他模型都可以使用的接口

它甚至使用您的
model\u id
/
model
列,但称它们为
X\u id
X\u type
,其中
X
是关联名称:

class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      #...
      t.integer :imageable_id
      t.string  :imageable_type
      #...
    end
  end
end
class CreatePictures
在你的情况下,你会有这样的东西:

class ApiCredential < ActiveRecord::Base
  belongs_to :creditable, :polymorphic => true
end

class Pancake < ActiveRecord::Base
  has_many :api_credentials, :as => :creditable
end

class OneCentStamp < ActiveRecord::Base
  has_many :api_credentials, :as => :creditable
end
类ApiCredentialtrue 结束 类Pancake:可信 结束 类OneCentStamp:可信 结束
感谢您提醒我多态性和快速响应。我想这正是我需要的。让我快速看一下!这正是我想要的。非常感谢。我所做的唯一区别是我将我的模型关联起来,使得煎饼有一个顶点。希望没有问题。@daemonsy:应该可以与
has_one
:(请参阅4.2.2.1)配合使用。