Search code examples
ruby-on-railsparametersself

rails, how to pass self in function


message and user. my message belongs_to user and user has_many messages.

in one of my views, i call something like

current_user.home_messages?

and in my user model, i have...

  def home_messages?
    Message.any_messages_for
  end

and lastly in my message model, i have

scope :any_messages_for

    def self.any_messages_for
        Message.where("to_id = ?", self.id).exists? 
    end

ive been trying to get the current_users id in my message model. i could pass in current_user as a parameter from my view on top but since im doing

current_user.home_messages?

i thought it would be better if i used self. but how do i go about referring to it correctly?

thank you.


Solution

  • You could use a lambda. In your Message model:

    scope :any_messages_for, lambda {|user| where('user_id = ?', user.id)}
    

    This would work like so:

    Message.any_messages_for(current_user)
    

    And you could add a method to your user model to return true if any messages are found. In this case you use an instance method and pass in the instance as self:

    def home_messages?
      return true if Message.any_messages_for(self)
    end
    

    But really, I'd just do something like this in the User model without having to write any of the above. This uses a Rails method that is created when declaring :has_many and :belongs_to associations:

    def home_messages?
      return true if self.messages.any?
    end