Create method for has_many relationship?
Model Post
has_many :comments
has_mant :tags
def comments?
!self.comments.empty?
end
def tags?
!self.tags.empty?
end
To check specific post has any comments or ta开发者_StackOverflow社区gs. I have written a instance method comment? and tags? which will return true or false on the basis of post has comments and tags or not.
I want to write a method for all has_many relationship which will provide method with '?'.
So In future If I have 10 has_many relationship with post than I don't need to write 10 methods for relation1?, relation2?.
Any Idea.
If you want dynamically defined methods, like ActiveRecord does for various things, you can do:
class Model
has_many :x
has_many :y
self.reflect_on_all_associations(:has_many).each do |association|
define_method "#{association.name}?" do
self.send(association.name).any?
end
end
end
This will create methods :x?
and :y?
. You can put this in a module, and include it into the models you need.
Edit: any?
is the same as !
and empty?
精彩评论