简体   繁体   English

Rails提交带有从url获取参数的表单

[英]Rails submit form with get parameters from url

I have form for signup user and when this url have get parameter like http://localhost:3000/signup?list_id=10 need transfer this parameters to action for create user 我有注册用户的表单,当此url具有诸如http://localhost:3000/signup?list_id=10类的get参数时,需要将此参数传递给创建用户的操作

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

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

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

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

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

<%= f.submit yield(:button_text), class: "btn btn-primary" %>

in this action user create dont see this parameter 在此操作中,用户创建看不到该参数

  def create
debugger
@user = User.new(user_params)
if @user.save
  log_in @user
  flash[:success] = "Welcome to the Sample App!"
  redirect_to @user
else
  render "new"
end

end 结束

(byebug) params<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"I5+lc0T2fqy2Ie56rMnkR6Eff60nJmiuaTob7xAqknB6YgHZpmEByyRpCanpnNqyO9H/wMWbm7IumdXRyUABcA==", "user"=>{"name"=>"Ivan", "email"=>"ss@ss.com", "password"=>"222", "password_confirmation"=>"222"}, "commit"=>"Create my account", "controller"=>"users", "action"=>"create"} permitted: false>

It's available in your params hash so you can add it to your form as a hidden field so it will be submitted with the other params. 它在params哈希中可用,因此您可以将其作为隐藏字段添加到表单中,以便与其他params一起提交。 Then make sure to whitelist that parameter in your controller. 然后确保在控制器中将该参数列入白名单。

First, add the virtual attribute to your User model if :list_id isn't already a persisted attribute for Users. 首先,如果:list_id还不是用户的持久属性,则将虚拟属性添加到您的用户模型。 This is done by adding the following line in your user.rb model file: 这是通过在user.rb模型文件中添加以下行来完成的:

attr_accessor :list_id

Then add the following inside your form view: 然后在表单视图中添加以下内容:

<%= f.hidden_field :list_id, :value => params[:list_id] %>

Then in your controller where you whitelist your params you would add :list_id as a secure parameter. 然后,在将参数列入白名单的控制器中,您将添加:list_id作为安全参数。 You didn't post your strong_params method but should be like: 您没有发布您的strong_params方法,但是应该像这样:

def user_params
    params.require(:user).permit(:list_id, :name, :email, :password, :password_confirmation)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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