将操作发布到阵列时出错

时间:2014-06-17 21:19:59

标签: ruby-on-rails arrays mailboxer

我使用rails mailboxer来处理我的应用通知。我已经能够按照documentation中的说明向单个用户发送通知,但我无法弄清楚如何向一组用户发送通知。在我的情况下,他们的粉丝。

当我尝试发送到数组时出现此错误:

undefined method `notify_all' for #<Array:0x696faf8>

我的模特:

class Update < ActiveRecord::Base
    belongs_to :member
    belongs_to :updateable, polymorphic: true
    attr_accessible :title, :content

    after_create :create_notification, on: :create

    def create_notification
    subject = "#{member.user_name}"
    body = "posted a new update <b>#{title}:</b> <p><i>#{content}</i></p>"
    updateable.followers.notify_all(subject, body, self)
    end
end

我的控制器:

class UpdatesController < ApplicationController
    before_filter :authenticate_member!
    before_filter :load_updateable
    before_filter :find_member

    def index
        redirect_to root_path
    end

    def new
        @update = @updateable.updates.new
    end

    def create
        @update = @updateable.updates.new(params[:update])
        @update.member = current_member

        respond_to do |format|
        if @update.save
            format.html { redirect_to @updateable }
            format.json { render json: @updateable }
        else
            format.html { redirect_to @updateable }
            format.json { render json: @updateable.errors, status: :unprocessable_entity }
        end
    end 
end

def destroy
    @update = Update.find(params[:id])

    respond_to do |format|
      if @update.member == current_member || @updateable.member == current_member
        @update.destroy
        format.html { redirect_to :back }
      else
        format.html { redirect_to :back, alert: 'You can\'t delete this update.' }
      end
    end 
end

private

# def load_updateable
#       resource, id = request.path.split('/')[1,2] # photos/1/
#       @updateable = resource.singularize.classify.constantize.find(id) #    Photo.find(1)
# end 

# alternative option:
def load_updateable
    klass = [Project, Event].detect { |c| params["#{c.name.underscore}_id"] }
    @updateable = klass.find(params["#{klass.name.underscore}_id"])
end

def find_member
    @member = Member.find_by_user_name(params[:user_name])
end 

end

2 个答案:

答案 0 :(得分:1)

正如jsksma2强调的那样,您可以将模型更改为:

class Update < ActiveRecord::Base
  belongs_to :member
  belongs_to :updateable, polymorphic: true
  attr_accessible :title, :content

  after_create :create_notification, on: :create

  def create_notification
    subject = "#{member.user_name}"
    body = "posted a new update <b>#{title}:</b> <p><i>#{content}</i></p>"
    updateable.followers.each { |follower| follower.notify_all(subject, body, self) }
  end
end

答案 1 :(得分:0)

如果您阅读错误,它会清楚地说明您的问题:您正在尝试调用阵列上的方法。数组类不知道notify_all是什么,所以它是undefined

您的直接解决方案如下:

array.each do |obj|
  obj.notify_all
end

假设数组中包含的对象是正确的类(它们包含方法)。

根据您的方法的命名约定来判断,我猜它是为处理数组而设计的;我建议重构你的方法更像是:

Class.notify_all(array)