我一直在 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