Search code examples
ruby-on-railsparameters

Rails and whitelist paramaters when using form_with without model,


Here is my  stuation, rails 6, I m trying to impliment Mail Controller for "contact us" page  and it's traight forward, route, controlerand call the mailer controller, all works, I reacieve the email, except getting the params from the view to mailer and when white listing the params, here "name" I get an error for the token.

#route
  get "/contact-us", to: 'home#contact', as: 'home_contact' 
  post "/contact-us", to: 'home#contact_send_email', as: 'home_contact_send_email' 
##############################
#controller page 
...
 def contact
 end

def contact_send_email # POST Method 

UserMailer.with(contact_params).contact_email.deliver_later
    redirect_to( home_contact_path)
  end   
private
def contact_params
      params.permit(:name) 
end
...
#################################
# view # home >contact.html.erb

...
<%= form_with( url:  home_contact_send_email_path, method: "post") do |form| %>
<%= form.label :name, class:"label" %>
<%= form.text_field :name, class:" field input is-medium"%>
...

##################################
console puts this error :
Unpermitted parameters: :authenticity_token
  • I tried using: params.require(:home).permit(:name) but I got the params for home are empty.

My question, is it possible, without creating any model, to whitelist paramaters when using form_with url, how can I do that ? if not is there a better way?


Solution

  • I don't see anything wrong with the message (it's not an error).

    I guess your params hash looks something like:

    {
      name: 'some_name',
      controller: 'home',
      action: 'contact_send_mail',
      authenticity_token: '............'
    }
    

    So your contact_params is sending a 'hash-like' object with the name permitted and the authenticity_token not permitted. The message you see makes sense since you are passing a hash with an unpermitted key.

    I mean, there's no error, you say it works, and the message you see means that strong parameters are actually working as intended (you are passing more keys than the expected ones and it tells you that).