开发者

Mongoid and ActiveRecord relations: undefined method `quoted_table_name'

开发者 https://www.devze.com 2023-03-27 16:01 出处:网络
class Contest < ActiveRecord::Base has_one :claim_template end class ClaimTemplate include Mongoid::Document
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开发者_JAVA百科_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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消