Bab*_*nov 15 activerecord ruby-on-rails associations
例如,有一些模型
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
Run Code Online (Sandbox Code Playgroud)
如何检查该模型是否具有has_many关联?像这样的东西
class ActiveRecord::Base
def self.has_many_association_exists?(:association)
...
end
end
Run Code Online (Sandbox Code Playgroud)
它可以这样使用
Model_1.has_many_association_exists?(:images) # true
Model_2.has_many_association_exists?(:images) # false
Run Code Online (Sandbox Code Playgroud)
提前致谢
KAR*_*ván 20
Model_1.reflect_on_association(:images)
Run Code Online (Sandbox Code Playgroud)
或者reflect_on_all_associations:
associations = Model_1.reflect_on_all_associations(:has_many)
associations.any? { |a| a.name == :images }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8109 次 |
| 最近记录: |