shuba.ivan
shuba.ivan

Reputation: 4071

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

<%= 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"=>"[email protected]", "password"=>"222", "password_confirmation"=>"222"}, "commit"=>"Create my account", "controller"=>"users", "action"=>"create"} permitted: false>

Upvotes: 1

Views: 3668

Answers (2)

Yshmarov
Yshmarov

Reputation: 3749

a better way that does not mess with the form would be to pass the params in the form url:

<%= form_with(model: @user, url: user_path(list_id: params[:list_id]) do |f| %>
...

Now you have params[:list_id] accessbile in your #create action.

it's just that simple!

Upvotes: 0

bkunzi01
bkunzi01

Reputation: 4561

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. 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. This is done by adding the following line in your user.rb model file:

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. You didn't post your strong_params method but should be like:

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

Upvotes: 2

Related Questions