Multiple require & permit strong parameters rails 4

旧城冷巷雨未停 提交于 2020-12-05 05:44:05

问题


In the below case, i am trying to use strong parameters. I want to require email_address, password and permit remember_me fields.

But using like below it only allows the LAST line in the method Ex:- In below case it only take params.permit(:remember_me)

  private

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

Another Ex:- In this below case, if i rearrange it like below it will take only params.require(:email_address) where am i going wrong ?

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

UPDATE Params hash be like

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

回答1:


Ok found the answer through a friend ...one way to do this is

params.require(:email_address)
params.require(:password)
params.permit(
:email_address,
:password,
:remember_me
)

Works good.




回答2:


Stong parameters are to prevent mass-assignment to Active Record models. Your parameters should be set up in a model backed form. Example from the Michael Hartl Tutorial:

REGISTRATION FORM

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

This will create a parameter that looks like:

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"
}

Then in your registration controller you can use strong parameters like:

STRONG PARAMETERS

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

It looks like in your case, you are handling a log in, in which case, you only need to use regular parameters to capture the login information.

SESSION CREATION

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



回答3:


Edit:

Here is the Rails way for you to handle logins and, I believe, cases where you need to 'require' multiple parameters and provide errors back to the user.

Unlike using strong params, this approach provides feedback to the user (using validation errors) when parameters are missing or blank. This is more user-friendly than throwing an exception.

  1. Create an ActiveModel (not ActiveRecord) form backing object. This form backing object is where you specify which fields are required and when a call to valid? is performed, these fields will be validated.

    With this, you will get nice user-friendly errors if:

    • email is missing
    • password is missing
    • email and password do not match

    models/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. Create the controller. Here is what your controller would look like for logging in a user:

    app/controllers/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. Set up the view

    app/views/sessions/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. Lastly, make sure the routes are configured

    config/routes.rb

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



回答4:


2020 solution:

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


来源:https://stackoverflow.com/questions/32613499/multiple-require-permit-strong-parameters-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!