Ruby on rails Rails-属于模型,其中模型可以是实现关系的任何模型?
可以在Rails 3中实现关联吗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
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
类ApiCredential感谢您提醒我多态性和快速响应。我想这正是我需要的。让我快速看一下!这正是我想要的。非常感谢。我所做的唯一区别是我将我的模型关联起来,使得煎饼有一个顶点。希望没有问题。@daemonsy:应该可以与
has_one
:(请参阅4.2.2.1)配合使用。