Search code examples
ruby-on-railsmailersubject

is it possible to use an instance or variable in the subject of rails mailer and how please :)


I would like to use an instance or variable like below in the mailer subject. So I would like to get the user name or some other user detail in the subject, I tried several thing but I receive an error every time. I can't find documentation about this either.

    mail(:to => "test@gmail, :subject => "current_user.name") or "<%= current_user.name %>"


class PositionMailer < ActionMailer::Base
  default from: "test@gmail.com"
  layout 'mailer'

  def general_message(position, barge_name)

    @position = position
    @barge_name = barge_name


    mail(:to => "1234@gmail.com, :subject => "#{barge_name}")
  end
end

controller

  def create
    @position = Position.new(position_params)
    if @position.save!
      redirect_to @position
      PositionMailer.general_message(@position, @barge_name).deliver

Solution

  • To pass a variable inside quotes you need to do it like this "#{variable.value}

    :subject => "#{current_user.name}" 
    

    should do it if it has access to current_user

    You will have to pass current_user to the mailer along with the position value.

    So wherever you are calling that from add current_user, probably looks something like this.

    PositionMailer.general_message(position, current_user).deliver