user4227507
user4227507

Reputation:

Ruby on Rails, send multiple emails simultaneously

Ok, in my RoR application I have a cinema system where users have preferences, which include saving their favourite actor. What I am trying to do is get it so that when a new film is added, if users have the any of film's actors saved as their favourite they will get an email notifying them of the film.

At the minute I can get it so that, through using a where statement, when a film is added the FIRST user in the array is emailed, films_controller:

def create
    @film = Film.new(film_params)
    if @film.save
        if not @film.cast1.blank?
            user1 = Perference.where(actor: @film.cast1).first.user
            if not user1.blank?
                actor = @film.cast1
                FavouriteActor.favourite_actor(user1, actor).deliver
            end
        end
        if not @film.cast2.blank?
            user2 = Perference.where(actor: @film.cast2).first.user
            if not user2.blank?
                actor = @film.cast2
                FavouriteActor.favourite_actor(user2, actor).deliver
            end
        end
        if not @film.cast3.blank?
            user3 = Perference.where(actor: @film.cast3).first.user
            if not user3.blank?
                actor = @film.cast3
                FavouriteActor.favourite_actor(user3, actor).deliver
            end
        end
        redirect_to @film
    else
        render 'new'
    end
end

This then goes to the favourite_actor.rb mailer:

class FavouriteActor < ApplicationMailer
 def favourite_actor(user, actor)
    @user = user
    @actor = actor
    @url  = 'http://localhost:3000/films'
    mail(to: @user.email, subject: 'Your favourite actor stars in a new film')
 end
end

Which then sends the favourite_actor.html.erb email

But what can I do to replace this lines like: user1 = Perference.where(actor: @film.cast1).first.userso that all the users with that actor as their favourite are emailed?

Upvotes: 1

Views: 71

Answers (2)

RAJ
RAJ

Reputation: 9747

You need to update your queries a bit:

preferences = Preference.where(["actor = ? OR actor = ? OR actor = ?", @film.cast1, @film.cast2, @film.cast3]).includes(:user)

preferences.each do |preference|
  FavoriteActor.favourite_actor(preference.user, actor).deliver
end

Upvotes: 2

Adam Bronfin
Adam Bronfin

Reputation: 1279

Perhaps try something like:

users = Preference.where(actor: @film.cast1)
users.each do |user|
  FavoriteActor.favourite_actor(user, actor).deliver
end

If I understand what you are wanting to do correctly, this will find all users with that favorite actor, iterate through the set and email each.

Upvotes: 0

Related Questions