[英]How get params from link ruby on rails?
I have column inviter
in my User model. 我的用户模型中有列
inviter
。 I want get params from the link and save it in cookies. 我想从链接中获取参数并将其保存在Cookie中。 For example, from this link:
例如,从此链接:
domain.com/?ref=5
I want save to cookies number ?ref=**5**
我想保存到Cookie编号
?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. 并且,当用户进行注册时,该用户将不需要在表单中输入推荐编号,因为它已经在cookie中。
<%= 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. 邀请号码将使用
?ref=**5**
并注册新用户。
Add something like this to your application_controller.rb
: 将类似的内容添加到
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]
. 更好的方法是使用隐藏的输入,并使用
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. 它需要较少的解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.