ruby-on-railsrubycookiesparametersgetparameter

How get params from link ruby on rails?


I have column inviter in my User model. I want get params from the link and save it in cookies. For example, from this link:

domain.com/?ref=5

I want save to cookies number ?ref=**5**

And when a user goes to registration, the user will not need to write in the number of the referral in the form, because it is already in cookies.

<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>

<%= f.label :name,'Your name'%>
<%= f.text_field :name, class: 'form-control' %>

<%= f.label :email,'Email' %>
<%= f.email_field :email, class: 'form-control' %>

<%= f.label :invite, 'Number who invited you' %>
<%= f.text_field :invite, class: 'form-control' %>

<%= f.label :password, 'password' %>
<%= f.password_field :password, class: 'form-control' %>

<%= f.label :password_confirmation ,'password confirmation' %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>
<br>
    <br>
    <div class="textc">
    <%= f.submit yield(:button_text), class: "formbut" %>
    </div>
<% end %>

The invite number will use ?ref=**5** and register the new user.


Solution

  • Add something like this to your application_controller.rb:

    before_action :store_ref
    
    private
    
    def store_ref
      cookies[:ref] = params[:ref] if params[:ref].present?
    end
    

    And something like this to your user create action:

    def create
      @user = User.new(user_params)
      @user.ref = cookies[:ref]
    
      if @user.save
      # ...