简体   繁体   中英

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.

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
  # ...

A better approach would be to use a hidden input and populate it with the value from params[:ref] .

class UsersController < ApplicationController
  def new
    @user = User.new do |u|
      if params[:ref].present? 
        u.inviter = params[:ref]
      end
    end
  end

  # ...
end

<%= form_for(@user) do |f| %>
  # ...
  <% if f.object.inviter.present? %>
    <%= f.hidden_field :inviter %>
  <% end %>
<% end %>

It requires less workarounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM