Ruby on Rails:具有强params

时间:2017-03-03 09:09:46

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 strong-parameters

在我的RoR应用程序中,我有一个update_multiple方法,可以使用用户的输入更新多个记录。但是,出于某种原因,尽管使用了强大的参数,我仍然会收到错误ActiveModel::ForbiddenAttributesError。有人可以帮我解决这个问题吗?

Recipients_Controller中的update_multiple方法如下:

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

此方法从此表单中获取用户输入:

<%= 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 %>

development.log读取此内容:

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)

如果它显示app/controllers/recipients_controller.rb:15:in 'update_multiple',则表示行if Recipient.update(params[:recipient].keys, params[:recipient].values)

我真的无法弄清楚为什么我会收到这个错误。有人可以帮助我吗?

我已经查看了其他各种SO问题,它们似乎已由strong_params解决,但我已经声明strong_params并且无效。

2 个答案:

答案 0 :(得分:3)

问题在于这一行:

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

您正在将params直接传递给update方法。您需要将recipient_params传递给update

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

<强>更新

但是,从您的日志中,很明显params [:recipient]返回包含id / attribute对的哈希,而不是一组属性。因此,您需要允许id中传递的每个收件人params的属性。我认为这段代码应该这样做:

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

答案 1 :(得分:0)

评论后编辑答案

首先,一些好docs帮助您更好地了解如何使用强参数。

现在,让我们尝试重构你的代码。请记住,大于4行的方法隐藏错误的风险更大,如果可以的话,请避免使用它们!

这是你的代码,除了我将一些代码块移动到子方法

之外,我什么都没改变
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

现在解决方案可能就像这样

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

当然我无法测试它,可能它会在某处崩溃,但或多或​​少这是个主意。