brad
brad

Reputation: 1695

how to pass multiple objects into mailer/email contents in rails

When an user makes a post (sub_opp) I send the user an email. However, I would like to include in the email the sport (column in sub_opp model). I am getting an undefined method error on sub_opp when it hits the mailer in the example below.

Controller where sub_opp is created

def create
@sub_opp = SubOpp.new(sub_opp_params)
respond_to do |format|
  if @sub_opp.save
    user = User.find_by_id(@sub_opp.user_id)
    sub_opp = @sub_opp
    UserMailer.posted_subopp_email(user, sub_opp).deliver
    .... continued

Mailer controller

  def posted_subopp_email(user, sub_opp)
    mail( :to => user.email,  :subject => 'You made a post!' )
  end

Mailer view

<!DOCTYPE html>
 <html>
  <head>
   <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h3>You posted to the sub feed!</h3>
    <p>You made a post.</p>
    <p><%= sub_opp.sport %></p>
  </body>
 </html>

Why doesn't the <%= sub_opp.sport %> work in this example? Sport is a column in the sub_opp model.

Thanks

Upvotes: 3

Views: 2100

Answers (1)

mathieugagne
mathieugagne

Reputation: 2495

Create an instance variable first. Instance variables will be available in your mailer view.

Consider your mailer a controller in MVC.

def posted_subopp_email(user, sub_opp)
  @sub_opp = sub_opp
  @user = user
  mail( :to => user.email,  :subject => 'You made a post!' )
end

Then access it like in you would in your views

<body>
  <h3>You posted to the sub feed!</h3>
  <p>You made a post.</p>
  <p><%= @sub_opp.sport %></p>
</body>

Upvotes: 8

Related Questions