Ответ 1
Как насчет reflect_on_association
?
Model_1.reflect_on_association(:images)
Или reflect_on_all_associations
:
associations = Model_1.reflect_on_all_associations(:has_many)
associations.any? { |a| a.name == :images }
Например, есть несколько моделей
class Model_1 < ActiveRecord::Base
has_many :images, :as => :imageable
end
class Model_2 < ActiveRecord::Base
# doesn't have has_many association
end
...
class Image < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
Как проверить, имеет ли модель has_many связь? Что-то вроде этого
class ActiveRecord::Base
def self.has_many_association_exists?(:association)
...
end
end
И его можно использовать так
Model_1.has_many_association_exists?(:images) # true
Model_2.has_many_association_exists?(:images) # false
Заранее спасибо
Как насчет reflect_on_association
?
Model_1.reflect_on_association(:images)
Или reflect_on_all_associations
:
associations = Model_1.reflect_on_all_associations(:has_many)
associations.any? { |a| a.name == :images }
Возможно, вы можете использовать response_to?
class ActiveRecord::Base
def self.has_many_association_exists?(related)
self.class.associations.respond_to?(related)
end
end
Я нашел следующее, чтобы быть простым способом достижения желаемого результата:
ModelName.method_defined?(:method_name)
Пример:
Model_1.method_defined?(:images) # true
Model_2.method_defined?(:images) # false
Ссылка: fooobar.com/questions/63121/...
У вас может быть только метод, который пытается получить доступ к изображениям объекта Model_1 внутри блока исключений вроде (примерно):
begin
model1_obj.images
rescue
puts 'No association between model_1 and images'
end
Внутри спасения вы можете просто вернуть false, если хотите.