1

我一直在 Rails 应用程序中构建消息传递,以便用户能够相互发送消息。我查看了一些 gem,例如 mailboxer,但最终决定自己构建。

我希望有人能帮我把这些碎片放在一起。我一直在这里关注类似问题的答案。

我正在 Rails 控制台中进行测试,但我不断收到以下错误:

未定义的方法 `send_message' 用于#

我怎样才能解决这个问题?

控制器

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

路线

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

消息模型

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
4

1 回答 1

4

您正在类级别调用该方法:Message.send_message. 为此,它需要这样的声明:

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

但是,你得到了这个:

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

因此,要么在您需要的实例上调用该方法,要么重构以使其在类级别上工作。

于 2012-11-07T21:01:45.153 回答