DaveG
DaveG

Reputation: 1203

User to User Messages in Rails

I've been building messaging in a rails app for users to be able to send each other messages. I've looked at a few gems such as mailboxer but ultimately decided to build my own.

I'm hoping someone can help me put these pieces together. I've been following a similar question's answer here.

I'm testing in the rails console and I keep getting the following error:

undefined method `send_message' for #

How can I fix this?

Controller

class MessagesController < ApplicationController
    # create a comment and bind it to an article and a user  
    def create
      @user = User.find(params[:id])
      @sender = current_user
      @message = Message.send_message(@sender, @user)
      flash[:success] = "Message Sent."
      flash[:failure] = "There was an error saving your comment (empty comment or comment way to long)"
    end
end

Routes

  resources :users, :except => [ :create, :new ] do
     resources :store
     resources :messages, :only => [:create, :destroy] 
  end

Messages Model

class Message < ActiveRecord::Base
  belongs_to :user

  scope :sent, where(:sent => true)
  scope :received, where(:sent => false)

  def send_message(from, recipients)
     recipients.each do |recipient|
       msg = self.clone
       msg.sent = false
       msg.user_id = recipient
       msg.save
     end
     self.update_attributes :user_id => from.id, :sent => true
   end
end

Upvotes: 1

Views: 972

Answers (1)

dimitarvp
dimitarvp

Reputation: 2383

You are invoking the method on a class level: Message.send_message. For this to work, it would expect a declaration like this:

def self.send_message(from, recipients)
  # ...
end

But, you got this instead:

def send_message(from, recipients)
  # ...
end

So, either invoke the method on the instance you need it for, or refactor to make it work on a class level.

Upvotes: 4

Related Questions