多个要求&允许强参数rails 4

时间:2015-09-16 15:59:56

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller strong-parameters

在下面的例子中,我试图使用强参数。我想要email_address, password并允许remember_me字段。

但是使用如下所示它只允许方法Ex中的最后一行: - 在下面的情况下,只需要params.permit(:remember_me)

  private

  def registration_params
    params.require(:email_address)
    params.require(:password)
    params.permit(:remember_me)
  end

另一个例子: - 在下面这种情况下,如果我重新安排它,如下所示只会params.require(:email_address)我错在哪里?

  def registration_params
    params.require(:password)
    params.permit(:remember_me)
    params.require(:email_address)
  end

更新 Params hash就像

{
              "utf8" => "✓",
     "email_address" => "test1@gmail.com",
          "password" => "password123",
       "remember_me" => "true",
            "commit" => "Log in",
        "controller" => "registration",
            "action" => "sign_in"
}

4 个答案:

答案 0 :(得分:7)

好的,通过朋友找到答案......一种方法是

stuff = stuff || {};

// if stuff is already defined, just leave it be. If not (||), define it as object

stuff[userId] = stuff[userId] || {};

// if stuff[userId] is already defined, define it as self (let it be unchanged). If not defined ( the || -signs ), define it as object.

stuff[userId][objectId] = stuff[userId][objectId] || {};

// and so on :)

效果很好。

答案 1 :(得分:0)

修改

以下是您处理登录的Rails方式,我相信,您需要“处理登录”的情况。多个参数并将错误提供给用户。

与使用强params不同,此方法在参数缺失或空白时向用户提供反馈(使用验证错误)。这比抛出异常更加用户友好。

  1. 创建一个ActiveModel不是 ActiveRecord)表格支持对象。此表单支持对象是您指定所需字段的位置,当执行对valid?的调用时,将验证这些字段。

    有了这个,如果出现以下情况,您将获得良好的用户友好错误:

    • 电子邮件丢失
    • 密码丢失
    • 电子邮件和密码不匹配

    <强>模型/ session.rb

    class Session
      include ActiveModel::Model
    
      attr_accessor :password, :email, :remember_me
    
      validates_presence_of :password, :email        # these fields are required!
    
      def authenticate
        return false unless valid?   # this checks that required params
                                     # are present and adds errors to the
                                     # errors object if not
    
        if User.authenticate(:password, :email)  # validate credentials
          true
        else              
          errors.add(:email, "and password didn't match")  # wrong credentials. add error!
          false
        end
      end
    end
    
  2. 创建控制器。以下是您的控制器用于登录用户的样子:

    应用/控制器/ sessions_controller.rb

    class SessionsController < ApplicationController
      # GET /login
      def new
        @session = Session.new
      end
    
      # POST /login
      def create
        @session = Session.new(login_params)
        if @session.authenticate
          # do whatever you need to do to log the user in
          # set remember_me cookie, etc.
          redirect_to '/success', notice: 'You are logged in'
        else
          render :new   # shows the form again, filled-in and with errors
        end
      end
    
      private
    
      def login_params
        params.require(:session).permit(:email, :password, :remember_me)
      end
    end
    
  3. 设置视图

    应用/视图/会话/ new.html.erb

    <% if @session.errors.any? %>
      <ul>
        <% @session.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    <% end %>
    
    <%= form_for @session, :url => login_path do |f| %>
        <div>
          <%= f.label :email, 'Email:' %>
        </div>
        <div>
          <%= f.text_field :email %>
        </div>
        <div>
          <%= f.label :password, 'Password:' %>
        </div>
        <div>
          <%= f.password_field :password %>
        </div>
        <div>
          <%= f.label :remember_me, 'Remember Me?' %>
          <%= f.check_box :remember_me %>
        </div>
        <div>
          <%= f.submit %>
        </div>
    <% end %>
    
  4. 最后,确保已配置路线

    <强>配置/ routes.rb中

    get 'login' => 'sessions#new'
    post 'login' => 'sessions#create'
    

答案 2 :(得分:0)

强大的参数是为了防止质量分配到Active Record模型。您的参数应在模型支持的表单中设置。 Michael Hartl Tutorial的示例:

注册表

<%= form_for(@user) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :email %>
  <%= f.email_field :email %>

  <%= f.label :password %>
  <%= f.password_field :password %>

  <%= f.label :password_confirmation, "Confirmation" %>
  <%= f.password_field :password_confirmation %>

  <%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>

这将创建一个如下所示的参数:

PARAMS

{
          "utf8" => "✓",
 "user" =>  { email: "test1@gmail.com", name:"Test Name", password: "password", password_confirmation: "password" },
   "remember_me" => "true",
        "commit" => "Log in",
    "controller" => "registration",
        "action" => "sign_in"
}

然后在您的注册控制器中,您可以使用强大的参数,如:

强参数

params.require(:user).permit(:name, :email, :password, :password_confirmation)

在您的情况下,您正在处理登录,在这种情况下,您只需使用常规参数来捕获登录信息。

会话创建

def sign_in
   email = params[:email]
   password = params[:password]
   if User.authenticate!(email, password)
     # do something
   else 
     # do something different
   end
end

答案 3 :(得分:0)

2020解决方案:

def registration_params
  params.require([:email_address, :password])               #require all of these
  params.permit(:email_address, :password, :remember_me)    #return hash
end