【问题标题】:Is there any way to check that has_many association exists in Rails 3.1?有什么方法可以检查 Rails 3.1 中是否存在 has_many 关联?
【发布时间】:2011-11-26 20:40:45
【问题描述】:

例如有一些型号

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

提前致谢

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案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 }
    

    【讨论】:

    • 非常感谢!正是我需要的)
    【解决方案2】:

    我发现以下是达到预期结果的简单方法:

    ModelName.method_defined?(:method_name)
    

    例子:

    Model_1.method_defined?(:images) # true
    Model_2.method_defined?(:images) # false
    

    参考:https://stackoverflow.com/a/18066069/936494

    【讨论】:

    • 这种方法不完全兼容。例如,用 :destroy 试试。不是关系,但对象有这个方法。
    【解决方案3】:

    您可能会使用 respond_to?

    class ActiveRecord::Base
        def self.has_many_association_exists?(related)
            self.class.associations.respond_to?(related)
        end
    end
    

    【讨论】:

    • 我可能会接受 KARASZI István 的回答!
    【解决方案4】:

    您可以只使用一个方法来尝试访问异常块内的 Model_1 对象图像,例如(大致):

    begin
      model1_obj.images
    rescue
      puts 'No association between model_1 and images'
    end
    

    在救援中,如果你愿意,你可以返回 false。

    【讨论】:

    • 这可能是一个方法,或属性,或任何东西。不是协会。但是,是的,鸭子打字:)
    猜你喜欢
    • 2012-05-30
    • 1970-01-01
    • 2011-01-17
    • 2013-01-18
    • 2018-01-31
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多