Mongoid and ActiveRecord relations: undefined method `quoted_table_name'

巧了我就是萌 提交于 2019-12-06 08:34:51

问题


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

ok, let's add quoted_table_name to 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

So how can I configure my models to work properly with each other

PS:

Now I have this construction, which works fine, but I want to have benefits of Relations (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

回答1:


I am not sure if this has been formally implemented yet. Associations are handled mostly through ActiveRecord::Reflection, which is hardcoded to the idea of relational tables, see this class:

  • https://github.com/rails/rails/blob/master/activerecord/lib/active_record/reflection.rb

What that's suggesting is that there is no way ActiveRecord associations can work with things like Mongoid.

I recommend either building a gem to solve that problem by building a similar reflection wrapper for Mongoid, or just construct the associated objects manually.




回答2:


There is an interesting gem available called Tenacity which seems to do what you want, using t_has_one, t_has_many and t_belongs_to rather than the normal associations.

Because it currently only has those relations it is a bit limited, and I'm currently struggling with a many-to-many, but that may help you out.

Check it out here - https://github.com/jwood/tenacity



来源:https://stackoverflow.com/questions/7026981/mongoid-and-activerecord-relations-undefined-method-quoted-table-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!