Mongoid and ActiveRecord relations: undefined meth

2020-07-22 19:08发布

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

2条回答
【Aperson】
2楼-- · 2020-07-22 19:24

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

查看更多
唯我独甜
3楼-- · 2020-07-22 19:48

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:

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.

查看更多
登录 后发表回答