Rails 3中的消息传递



我正在使用http://www.novawave.net/public/rails_messaging_tutorial.html教程在我的ruby on rails项目上实现消息传递。我正在运行ruby 1.9.2和rails 3,并不断得到这个错误

NoMethodError in SentController#create  
undefined method 'each_line' for ["35"]:Array

应用程序跟踪:

app/models/message.rb:13:in 'prepare_copies'  
app/controllers/sent_controller.rb:24:in 'create'
消息模型:

1   class Message < ActiveRecord::Base  
2     belongs_to :author, :class_name => "User"  
3     has_many :message_copies  
4     has_many :recipients, :through => :message_copies  
5     before_create :prepare_copies  
6    
7     attr_accessor :to #array of people to send to  
8     attr_accessible :subject, :body, :to  
9  
10    def prepare_copies  
11      return if to.blank?  
12    
13      to.each_line do |recipient|  
14        recipient = User.find(recipient)  
15        message_copies.build(:recipient_id => recipient.id, :folder_id => recipient.inbox.id)  
16      end  
17    end  
18  end

发送控制器:

class SentController < ApplicationController  
  ...  
  def create  
    current_user = User.find(session[:user_id])  
    @message = current_user.sent_messages.build(params[:message])  
    if @message.save  
      flash[:notice] = "Message sent."  
      redirect_to :action => "index"  
    else  
      render :action => "new"  
    end  
  end  
end

如果我编辑并使用:

to.each do |recipient|  
  ...  
end

我得到一个不同的错误:

RuntimeError in SentController#create  
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

应用程序跟踪:

app/models/message.rb:15:in 'block in prepare_copies'  
app/models/message.rb:13:in 'each'  
app/models/message.rb:13:in 'prepare_copies'  
app/controllers/sent_controller.rb:24:in 'create'

您所提到的站点的正确代码片段是:

def prepare_copies
  return if to.blank?
  to.each do |recipient|
    recipient = User.find(recipient)
    message_copies.build(:recipient_id => recipient.id, :folder_id => recipient.inbox.id)
  end
end

这是第8个黑色帧

在数组中调用each的正确方法是使用第二个示例:

to.each do |recipient|  
  ...  
end

对于您收到的错误消息,对于您正在循环的给定to s,似乎没有User s存在(User.find()没有返回任何内容)。堆栈跟踪提示您在给定以下行时调用了一个nil对象的访问器id():

:recipient_id => recipient.id

创建一个模拟User,并仅向该用户发送一条消息,以验证这是否是导致错误的原因。如果是这样,你需要一些错误处理来确保你不会在nil记录上调用id()inbox()

另一种可能性是你有一个为nil的inbox,在这种情况下,你将在nil对象上再次调用id()

几天前,我用一个插件在我的应用程序上创建了一个消息传递系统,它运行得很好,完全支持Rails 3。

相关内容

  • 没有找到相关文章

最新更新