user3340009
user3340009

Reputation: 37

How do I extract one parameter from multiple request parameters using Rails?

If I want to get out one parameter from request parameters below, how do I do so?

{"utf8"=>"✓", "authenticity_token"=>"***", "users_unsubscribe_mail_magazine_form"=>{"email"=>"[email protected]", "dm"=>"1"}, "commit"=>"Send Mail", "controller"=>"users/unsubscribe_mail_magazines", "action"=>"create"}

I want to get "users_unsubscribe_mail_magazine_form"=>{"dm"=>"1"}, and pass the parameter to another page. When I type into the live shell

params[:users_unsubscribe_mail_magazine_form][:dm]

I get an error message

"!! #<NameError: undefined local variable or method `params' for #UnsubscribeMailMagazineMailer:0x00007f14c86c5848>"

Thank you.

PS: I am using form_for "f.submit" to send the parameters.

PPS: This is how I call my mailer.

    def create
      @unsubscribe_form = Users::UnsubscribeMailMagazineForm.new mail_magazine_unsubscribe_params
      @dm = @unsubscribe_form.dm
      if @unsubscribe_form.valid?
        user = User.find_by(email: @unsubscribe_form.email)
        UnsubscribeMailMagazineMailer.unsubscribe(user).deliver_now unless user.nil?
        redirect_to action: :create_complete
      else
        render action: :new
      end
    end

Upvotes: 1

Views: 391

Answers (1)

spickermann
spickermann

Reputation: 106782

The params are only available in the controller. When you want to use the parameters or single values from them in a mailer then you have to pass that value to the mailer in the arguments.

Something like this should work:

# in the controller
UnsubscribeMailMagazineMailer.unsubscribe(
  user, params[:users_unsubscribe_mail_magazine_form][:dm]
).deliver_now if user

# in your mailer
def unsubscribe(user, dm)
  # have the `user` and the `dm` value available in local variables
end
    

Upvotes: 1

Related Questions