How to remove a field from parameters [: something]

My registration form, which is the form for the Users model, takes a string value for the company. However, I just made a change, so users belong to companies. Therefore, I need to transfer the company object to the Users model.

I want to use a string value from a form to get a company object:

@user.company = Company.find_by_name(params[:company]) 

I believe the above works, however the form passes: company (which is a string) to the model when I call:

 @user = User.new(params[:user]) 

Therefore, I want to know (and cannot find how) to remove the: company parameter before passing it to the User model.

+84
ruby-on-rails
Mar 01 2018-11-11T00:
source share
4 answers

You can remove a key / value pair from a hash using Hash#delete :

 params.delete :company 

If it is contained in the [: user] parameters, you should use this:

 params[:user].delete :company 
+167
Mar 01 2018-11-11T00:
source share

You should probably use hash.except

 class MyController < ApplicationController def explore_session_params params[:explore_session].except(:account_id, :creator) end end 

It does 2 things: it allows you to simultaneously exclude more than one key and not change the original hash.

+64
Oct 21 '14 at 18:06
source share
 respond_to do |format| if params[:company].present? format.html {redirect_to(:controller=>:shopping, :action=>:index)} else format.html end 

this will remove the parameters from the url

+1
Feb 21 2018-12-12T00:
source share

The correct way to achieve this is to use strong_params

 class UsersController < ApplicationController def create @user = User.new(user_params) end private def user_params params.require(:user).permit(:name, :age) end end 

Thus, you have more control over what parameters should be passed to the model.

+1
Sep 20 '16 at 14:52
source share



All Articles