我一直在rails应用程序中构建消息,以便用户能够发送彼此的消息。我看了几个宝石,比如邮箱,但最终还是决定建立自己的宝石。
我希望有人可以帮我把这些碎片放在一起。我一直在关注类似问题的回答here。
我正在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
答案 0 :(得分:4)
您正在课程级别调用该方法:Message.send_message
。为了实现这一目标,它需要这样的声明:
def self.send_message(from, recipients)
# ...
end
但是,你得到了这个:
def send_message(from, recipients)
# ...
end
因此,要么在需要它的实例上调用方法,要么重构以使其在类级别上工作。