开发者

Create method for has_many relationship?

开发者 https://www.devze.com 2023-03-17 23:11 出处:网络
Model Post has_many :comments has_mant :tags def comments? !self.comments.empty? end def tags? !self.tags.empty?

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消