【发布时间】:2011-08-11 13:46:19
【问题描述】:
class Contest < ActiveRecord::Base
has_one :claim_template
end
class ClaimTemplate
include Mongoid::Document
belongs_to :contest
end
# console
Contest.new.claim_template
#=> NoMethodError: undefined method `quoted_table_name' for ClaimTemplate:Class
好的,让我们将quoted_table_name 添加到ClaimTemplate:
def self.quoted_table_name
"claim_templates"
end
# console
Contest.new.claim_template
#=> nil
# Cool!
# But:
Contest.last.claim_template
#=> TypeError: can't convert Symbol into String
那么如何配置我的模型以使其正常工作
PS:
现在我有了这个结构,它工作得很好,但我想获得关系的好处 (Assosiations)。
class Contest < ActiveRecord::Base
# has_one :claim_temlate
def claim_template
ClaimTemplate.where(:contest_id => self.id).first
end
# Mongoid going to be crazy without this hack
def self.using_object_ids?
false
end
end
【问题讨论】:
-
您希望获得什么“关系的好处”? ActiveRecord 关联在关联中的两个模型都是 ActiveRecord 对象的假设下运行,因此您不太可能将
has_one和belongs_to一起开箱即用地工作。 -
@Michael Fairley,我想使用所有
Associations方法通过竞赛创建新的CleimTemplate,制作嵌套表格和accepts_nested_attributes_for等等。就Mongoid和ActiveRecord而言,我认为将它们一起使用没有任何问题,它们只是抽象,它们可以轻松处理这种行为 -
@fl00r 确定 Mongoid 和 ActiveRecord 只是抽象,并且都建立在 ActiveModel 之上,但除非它们都公开完全相同的 API 并以兼容的方式存储关系元数据,(AFAIK 不是案例)我认为您无法使这种跨 odm 关系正常工作(当然无需大量重写)。
标签: ruby-on-rails ruby activerecord mongodb mongoid