与Devise混淆了强大的参数 [英] Confused about strong parameters with Devise

查看:197
本文介绍了与Devise混淆了强大的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Devise注册表(省略不相关的标记):

I have the following Devise registration form (with irrelevant markup omitted):

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { id: "payment-form" }) do |f| %>
  <%= f.fields_for resource.paid_account do |pa| %>
    <%= pa.collection_select :account_plan_id, @account_plans, :id, :name_with_price %>
  <% end %>
<% end %>

此表单分发以下HTML:

This form spits out the following HTML:

<select id="user_paid_account_account_plan_id" name="user[paid_account][account_plan_id]">
  <option value="2">Lite ($10.00/mo)</option>
  <option value="3">Professional ($20.00/mo)</option>
  <option value="4">Plus ($30.00/mo)</option>
</select>

然后,我的 ApplicationController

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(
        :email,
        :password,
        :paid_account => :account_plan_id # <-- THIS IS PROBABLY WRONG
      )
    end
  end
end

当我提交表单时,我收到PaidAccount (#2163736620)预期,得到ActionController ::参数(#2173083140)。

When I submit my form I get "PaidAccount(#2163736620) expected, got ActionController::Parameters(#2173083140)".

我也尝试过以下不给出错误,但它也不创建记录:

I've also tried the following which doesn't give an error, but it also doesn't create a record:

  u.permit(
    :email,
    :password,
    :paid_account => []
  )

我做错了什么?

推荐答案

显示您的两个型号(用户 PaidAccount ,我相信)会有很大的帮助。无论如何,假设用户 PaidAccount 具有一对一的关系,代码应该如下所示: / p>

Showing your two models (User and PaidAccount, I believe) would help a great deal. Regardless, assuming User has a one-to-one relationship with PaidAccount, the code should probably look like this:

class User < ActiveRecord::Base
  has_one :paid_account

  accepts_nested_attributes_for :paid_account
end

class PaidAcount < ActiveRecord::Base
  belongs_to :user
end

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(
        :email,
        :password,
        :paid_account_attributes => :account_plan_id
      )
    end
  end
end

查看日志,了解表单值的提交方式。 StrongPameters gem 活动记录的嵌套属性也应该是有帮助的。

Look at your logs to see how the form values are being submitted. The docs of the StrongPameters gem and Active Record's Nested Attributes should also be helpful.

这篇关于与Devise混淆了强大的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆