【问题标题】:Mongoid and ActiveRecord relations: undefined method `quoted_table_name'Mongoid 和 ActiveRecord 关系:未定义的方法 `quoted_table_name'
【发布时间】: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_onebelongs_to 一起开箱即用地工作。
  • @Michael Fairley,我想使用所有Associations 方法通过竞赛创建新的CleimTemplate,制作嵌套表格和accepts_nested_attributes_for 等等。就MongoidActiveRecord 而言,我认为将它们一起使用没有任何问题,它们只是抽象,它们可以轻松处理这种行为
  • @fl00r 确定 Mongoid 和 ActiveRecord 只是抽象,并且都建立在 ActiveModel 之上,但除非它们都公开完全相同的 API 并以兼容的方式存储关系元数据,(AFAIK 不是案例)我认为您无法使这种跨 odm 关系正常工作(当然无需大量重写)。

标签: ruby-on-rails ruby activerecord mongodb mongoid


【解决方案1】:

有一个有趣的 gem,叫做 Tenacity,它似乎可以做你想做的事,使用 t_has_one、t_has_many 和 t_belongs_to 而不是正常的关联。

因为它目前只有那些关系,所以它有点有限,我目前正在努力处理多对多,但这可能会对你有所帮助。

在这里查看 - https://github.com/jwood/tenacity

【讨论】:

  • 老兄的坚韧不再保持,你能为此推荐一些其他的宝石吗?
  • 在我发布这篇文章后不久我就没有碰过 Mongo(我搬到了另一个项目),所以我不知道目前的情况是什么,抱歉。
【解决方案2】:

我不确定这是否已经正式实施。关联主要通过ActiveRecord::Reflection 处理,它被硬编码为关系表的概念,请参见这个类:

这表明 ActiveRecord 关联无法与 Mongoid 之类的东西一起使用。

我建议通过为 Mongoid 构建一个类似的反射包装器来构建一个 gem 来解决这个问题,或者只是手动构建相关的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多