Answer the question
In order to leave comments, you need to log in
Rails how to find an object through its polymorphic relationship?
The database is mongodb, we use mongoid
The situation is as follows: The class country (Country)
Has many names through a polymorphic relationship:
(The reason is that you can find what it is by any name - is it a country?, a city? or a person? )
has_many :alternames, :as => :alternameable, :class_name => 'Altername'
class Altername
include Mongoid::Document
field :name, type: String
field :lang, type: String
belongs_to :alternameable, :polymorphic => true
end
I can not find a solution - how to get a Country by "name" - name (if, in principle, there is a Country with such a name)
Country.alternames.find_by(name: 'Vasya') doesn't work - says that unknown parameter alternames for Country:class
Answer the question
In order to leave comments, you need to log in
In general, I poorly understood the task, more precisely, how you solve it, but this of
course will not work, because has_many and all other possible connections have an instance of the class, and not the class.
That is, something like this should work for you.
Most likely, you need something like here:
Or variations (for example, add join, remove the name class, etc., already by context)
UPD :
I would in your case did concern
# app/models/concerns/alternameable.rb
module Alternameable
extend ActiveSupport::Concern
def self.included(base)
base.class_eval do
def has_altername_for?(name)
joins(:alternames).where(name: name, alternameable_type: self.name).present?
end
end
end
module ClassMethods
end
end
class Country
include Alternameable
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question