Supertracer Supertracer - 2 months ago 14
Ruby Question

Passing params to rails action mailer

I am using action mailer to email winners,

@result
array has records of participants who has won including their email.

@result=>[#<Participant id: 47, admin_id: nil, sweepstake_id: 8, participant_name: "gomez", participant_email: "rakesh.k@birdvision.in", participant_number: "12131245421", ip_addr: "127.0.0.1", answer: "nice", reg_time: nil, entry_opt_id: nil, created_at: "2015-09-03 12:15:48", updated_at: "2015-09-07 12:12:53">, #<Participant id: 47, admin_id: nil, sweepstake_id: 8, participant_name: "gomez", participant_email: "rakesh.k@birdvision.in", participant_number: "12131245421", ip_addr: "127.0.0.1", answer: "nice", reg_time: nil, entry_opt_id: nil, created_at: "2015-09-03 12:15:48", updated_at: "2015-09-07 12:12:53">]


But when i pass the result from my controller to the mailer, the result now only has id as string.
Parameters: {"result"=>["47", "47"]
}.
How can i pass the array result which has all the participant records?

Code in view page:

<%= link_to "Email Winners",email_winner_sweepstakes_path(:result=>@result) %>


Code in controller:

def email_winner
Rails.logger.info("***********************#{params.inspect}")
ParticipantMailer.winner_confirmation(params[:result]).deliver_now!

end


Code in mailer:

def winner_confirmation(result)
@result = result
@url = 'http://example.com/login'
Rails.logger.info("=================mailer=================")
Rails.logger.info(@result.inspect)
@result.each do |i|
mail(to: i.participant_email, subject: 'Congratulation')
end
end

Answer

You will have to find winners by ID, in this line:

<%= link_to "Email Winners", email_winner_sweepstakes_path(result: @result) %>

what you do is formulate the URL and you can't store objects its only string and what it did is it will call .id on @result

to fix that:

in your controller:

def email_winner
  @results = Participant.where("id in (?)", params[:result])
  ParticipantMailer.winner_confirmation(@results).deliver_now!
end