Ошибка при публикации действия в массив

Я использую почтовый ящик rails для обработки уведомлений моего приложения. Мне удалось отправить уведомление отдельным пользователям, как указано в их документации, но я не могу понять, как отправить уведомление массиву пользователей. В моем случае их последователи.

Я получаю эту ошибку при попытке отправить в массив:

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 ответа

Решение

Как подчеркнул 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

Если вы прочитаете ошибку, она ясно излагает вашу проблему: вы пытаетесь вызвать метод в массиве. Класс массива не знает что notify_all это так undefined,

Ваше немедленное решение будет что-то вроде:

array.each do |obj|
  obj.notify_all
end

Предполагая, что объекты, содержащиеся в массиве, являются правильным классом (они содержат метод).

Судя по соглашению об именах вашего метода, я предполагаю, что он предназначен для обработки массива; по которому я бы предложил рефакторинг вашего метода, чтобы он был больше похож на:

Class.notify_all(array)
Другие вопросы по тегам