Ben Smith
Ben Smith

Reputation: 819

Ruby on Rails: ActiveModel::ForbiddenAttributesError with strong params

In my RoR application, I have an update_multiple method that updates multiple records with the user's inputs. However, for some reason I get the error ActiveModel::ForbiddenAttributesError despite using strong params. Can someone please help me fix this?

The update_multiple method in Recipients_Controller is as follows:

def update_multiple
    @email = Email.find_by_id(params[:email_id])
    if Recipient.update(params[:recipient].keys, params[:recipient].values)
        @listofcontacts = Recipient.where("id in (?)", params[:recipient].keys)
        @account = Account.find_by_id(@email.account_id)
        @listofcontacts.each do |f|
            recipient_message = @email.message
            recipient_message = recipient_message.gsub("VAR1", f.var1)
            contact = Contact.find_by_id(f.contact_id)
            @unsubscribe = Rails.application.message_verifier(:unsubscribe).generate(contact.id)
            UserEmails.send_email(@email, @account, contact.email, @unsubscribe, recipient_message).deliver_now
        end
        flash[:notice] = "recipients were updated"
        redirect_to root_path
    else
        render 'edit_multiple'
    end
end

private
def recipient_params
  params.require(:recipient).permit(:contact_id, :group_id, :email_id, :var1, :var2, :var3)
end

This method takes the user input from this form:

<%= form_for :recipient, :url => update_multiple_recipients_path, :html => { :method => :put }  do %>
    <fieldset>
        <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
            <thead>
            <tr>
                <th>Contact</th>
                <% if @email_message.upcase.include? "VAR1" %><th>VAR1</th><% end %>
            </tr>
            </thead>
            <tbody>
                <%= hidden_field_tag :email_id, @email %>
                <% @recipients.each do |recipient| %>
                    <tr class="odd gradeX">
                        <%= fields_for "recipient[]", recipient do |recipient_fields| %>
                        <td><%= recipient_fields.label recipient.contact.firstname %> <%= recipient_fields.label recipient.contact.surname %></td>
                        <% if @email_message.upcase.include? "VAR1" %><td><%= recipient_fields.text_field :var1, :required => true, :maxlength => 20 %></td><% end %>
                        <% end %>
                    </tr>
                <% end %>
            </tbody>
        </table></br>
        <%= submit_tag 'Send Email', {:class => 'btn btn-primary'} %></br>
        <%= link_to "Back", edit_email_path(@email) %>
    </fieldset> 
<% end %>

The development.log reads this:

Started PUT "/recipients/update_multiple" for ::1 at 2017-03-03 09:33:10 +0000
Processing by RecipientsController#update_multiple as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"BJtQ56CW169tJ0Yqlc7BZNZk8SiTCauvkpNkXRUqVv4WESSS/DGFVDe3uQnfTxxDgif8lbg8THtmxHT9bOh0zw==", "email_id"=>"292", "recipient"=>{"635"=>{"var1"=>"ben"}}, "commit"=>"Send Email"}
  [1m[36mEmail Load (0.0ms)[0m  [1mSELECT  "emails".* FROM "emails" WHERE "emails"."id" = ? LIMIT 1[0m  [["id", 292]]
  [1m[35mRecipient Load (1.0ms)[0m  SELECT  "recipients".* FROM "recipients" WHERE "recipients"."id" = ? LIMIT 1  [["id", 635]]
  [1m[36m (0.0ms)[0m  [1mbegin transaction[0m
  [1m[35m (0.0ms)[0m  rollback transaction
Completed 500 Internal Server Error in 5ms (ActiveRecord: 1.0ms)

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
  app/controllers/recipients_controller.rb:15:in `update_multiple'


  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (1459.1ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (1449.1ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.0ms)
  Rendered C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (3305.2ms)

Where it says app/controllers/recipients_controller.rb:15:in 'update_multiple', it is pointing to the line if Recipient.update(params[:recipient].keys, params[:recipient].values)

I really cannot figure out why I am getting this error. Can someone please help me?

I have looked at various other SO questions and they seem to have been solved by strong_params, but mine already has strong_params declared and isn't working.

Upvotes: 0

Views: 857

Answers (2)

ReggieB
ReggieB

Reputation: 8212

The problems is this line:

if Recipient.update(params[:recipient].keys, params[:recipient].values)

You are passing params directly to the update method. You need to pass recipient_params into update:

if Recipient.update(recipient_params.keys, recipient_params.values)

Update

However, from your logs, it is apparent that params[:recipient] is returning a hash containing id/attribute pairs, not a single set of attributes. So you'll need to permit the attributes for each recipient id passed in params. I think this code should do it:

private
def recipient_params
  params.require(:recipient).permit(permit_for_each_recipient)
end

def permit_for_each_recipient
  params[:recipient].keys.inject({}){|h,k| h[k] = attributes_to_permit; h}
end

def attributes_to_permit
  [:contact_id, :group_id, :email_id, :var1, :var2, :var3]
end

Upvotes: 3

jonnyjava.net
jonnyjava.net

Reputation: 932

EDITING ANSWER AFTER COMMENTS

First of all, some good docs To help you to understand better how to use strong parameters.

Now, let's try to refactor a bit your code. Remember, methods larger than 4 lines are more risky to hide mistakes, avoid them if you can!

This is your code, I changed nothing except I moved some chunks of code into sub-methods

def update_multiple
  #this cannot  work because there is no instance to update
  if Recipient.update(params[:recipient].keys, params[:recipient].values)
    send_unsuscribe_emails
    flash[:notice] = "recipients were updated"
    redirect_to root_path
  else
    render 'edit_multiple'
  end
end

private

def recipient_params
  params.require(:recipient).permit(:contact_id, :group_id, :email_id, :var1, :var2, :var3)
end

def send_unsuscribe_emails
  @email = Email.find_by_id(params[:email_id])
  #this cannot work because params[:recipient].keys does not return a list of ids (probably you want womethink like recipients_params[:contact_id])
  @listofcontacts = Recipient.where("id in (?)", params[:recipient].keys)
  @account = Account.find_by_id(@email.account_id)
  @listofcontacts.each do |f|
    send_unsuscribe_email(f)
  end
end

def send_unsuscribe_email(f)
  recipient_message = @email.message.gsub("VAR1", f.var1)
  contact = Contact.find_by_id(f.contact_id)
  @unsubscribe = Rails.application.message_verifier(:unsubscribe).generate(contact.id)
  UserEmails.send_email(@email, @account, contact.email, @unsubscribe, recipient_message).deliver_now
end

and now the solution could be like this

def update_multiple
  @listofcontacts = Recipient.where("id in (?)", recipients_params[:contact_id])
  if @listofcontacts.update(recipient_params)
    send_unsuscribe_emails
    flash[:notice] = "recipients were updated"
    redirect_to root_path
  else
    render 'edit_multiple'
  end
end

private

def recipient_params
  params.require(:recipient).permit(:contact_id, :group_id, :email_id, :var1, :var2, :var3)
end

def send_unsuscribe_emails
  @email = Email.find_by_id(params[:email_id])
  @account = Account.find_by_id(@email.account_id)
  @listofcontacts.each do |f|
    send_unsuscribe_email(f)
  end
end

def send_unsuscribe_email(f)
  recipient_message = @email.message.gsub("VAR1", f.var1)
  contact = Contact.find_by_id(f.contact_id)
  @unsubscribe = Rails.application.message_verifier(:unsubscribe).generate(contact.id)
  UserEmails.send_email(@email, @account, contact.email, @unsubscribe, recipient_message).deliver_now
end

Of course I cannot test it so, probably it will crash somewhere, but more or less this is the idea.

Upvotes: 0

Related Questions