Kavitha Velayutham
Kavitha Velayutham

Reputation: 703

Access a instance method from other model in ruby on rails?

I have a user model in my application. Now I want to replace some user model coding into 2 categories likely employ.rb and customer.rb under a module users, to avoid more number of codes in a single model. I want to access a method send_mail in customer.rb after a user created.

user.rb

after_create:send_msg_on_order

def send_msg_on_order
Users::Customer.send_mail
end

users/customer.rb

  def send_mail
  Mailer.send_mail_to_customer.deliver
  end

And I am getting undefined method `send_mail' for Users::Customer:Module error.

Upvotes: 0

Views: 749

Answers (2)

anusha
anusha

Reputation: 2135

You can also call like this

def send_msg_on_order
   Customer.send_mail
end

Upvotes: 0

Harsh Gupta
Harsh Gupta

Reputation: 4538

You have defined send_mail method as instance method but calling it as a class method. Either make it a class method or create an instance of Customer model and call it.

Making the method a class method:

def self.send_mail
  Mailer.send_mail_to_customer.deliver
end

If you wish to keep it an instance method, then call it like this:

after_create:send_msg_on_order

def send_msg_on_order
  Users::Customer.new.send_mail
end

HTH

Upvotes: 1

Related Questions