如何在rails 4中设置has_many列表的值?

时间:2014-07-05 01:26:41

标签: ruby-on-rails-4 oauth

对于具有多个授权的用户模型,我有以下表单:

= @user.inspect
= @auth.inspect

= form_for @user, :html => { :multipart => true } do |f|

  - if @user.errors.any?
    #error_explanation
      %h2= "#{pluralize(@user.errors.count, "error")} below."
      %ul
        - @user.errors.full_messages.each do |msg|
          %li.red-text= msg


  .field.ui-field-contain.ui-body
    = f.text_field :full_name, class: "ui-input-text primer corner all ui-shadow-inset", placeholder: "Full name"


  .field.ui-field-contain.ui-body.top-gap
    = f.text_field :email, class: "ui-input-text primer corner all ui-shadow-inset", placeholder: "email@example.com"

  .field.ui-field-contain.ui-body.top-gap
    = f.text_field :username, class: "ui-input-text primer corner all ui-shadow-inset", placeholder: "Username"

  .field.ui-field-contain.ui-body.top-gap
    = f.password_field :password, class: "ui-input-text primer corner all ui-shadow-inset", placeholder: "Password"

  = f.fields_for :authorizations do |a|
    = a.hidden_field :provider
    = a.hidden_field :uid

在UsersController上,我将每个参数的值设置如下:

  def set_values_for_provider
    auth_hash = request.env['omniauth.auth']

    if params[:provider] == 'facebook'
      @user.full_name = auth_hash.info.name
      @user.email = auth_hash.info.email
      @user.username = auth_hash.info.nickname
    else
      if params[:provider] == 'twitter'
        @user.full_name = auth_hash.info.name
        @user.username = auth_hash.info.nickname
      else 
        if params[:provider] == 'linkedin'
          @user.full_name = auth_hash.info.name
          @user.email = auth_hash.info.email
        end
      end
    end


  @auth = @user.authorizations.build


  @auth.provider = auth_hash.provider
  @auth.uid = auth_hash.uid
end

然而,授权的hidden_​​attributes的值未设置或保存。在页面的HTML中,我得到以下输出:

<input id="user_authorizations_provider" type="hidden" name="user[authorizations][provider]">
<input id="user_authorizations_uid" type="hidden" name="user[authorizations][uid]">

隐藏元素的值未设置,即使在检查时,auth对象同时显示:OAuth gem返回的provider和:uid值。有什么线索,我出错的地方?

更新:白名单如下:

# Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:full_name, :username, :email, :password, :cookie_token, :first_name, :middle_name, :last_name, :designation, :location, :gender, :user_image,:bio, :dob, authorization_attributes: [:provider, :uid])
    end

1 个答案:

答案 0 :(得分:1)

得到了我在强大的参数中犯的错误。 _nested_attributes_应该以复数形式列在白名单中:

authorizations_attributes: [:provider, :uid]

而不是

authorization_attributes: [:provider, :uid]

感谢@pavan带领我到现场。线程关闭。