Rails check if params exist in the controller
Solution 1
The problem is this line params.require(:primary)
saying that the parameter is required, so attempting to do like params.require(:primary).exists?
wont help you if you do not have a :primary
param at all because the require
already failed.
You need to check its existance on params
itself. For example params.has_key?(:primary)
.
Dependening on your use case, you might also use params.permit(:primary)
directly on params
as well. See the API docs for detailed information on how ActionController::Parameters
(the class for params
) can be used.
http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit
Solution 2
you can check your params existence in your case by params[:primary].present?
I think this is the easiest way
anonn023432
By day: I do my college homework and By Night: I do my college homework. Gotta work hard to get that degree
Updated on June 04, 2022Comments
-
anonn023432 almost 2 years
I have a
factor
controller which takes factor values for two different types of factors- Primary Factor
- Secondary Factor
And I pass them as params as follows:
class FactorController < AdminController def create if primary_factor_params ## LINE 5 do something elsif secondary_factor_params do something else end end def primary_factor_params params.require(:primary).permit(:user_id, ## LINE 70 :primary_factors) end def secondary_factor_params params.require(:secondary).permit(:user_id, :secondary_factors) end end
But in the above whenever I try to pass a
secondary_factor
I get the following error:ActionController::ParameterMissing (param is missing or the value is empty: primary): app/controllers/factors_controller.rb:70:in `primary_factor_params' app/controllers/api/v1/admin/factors_controller.rb:5:in `create'
So to me it seems that this error is coming up because I didn't have any values for
primary_factor_params
in this condition and that's way it throws the error because of the first if condition.I've tried:
primary_factor_params.exists? primary_factor_params.has_key?(:primary_factors) ....
But all of them throw the same error since
primary_factor_params
doesn't exist. Is there a way to test this without throwing an error for missing params? -
anonn023432 over 6 yearsYes, this makes perfect sense, I blanked out on the fact that I need to test on
params
becauseprimary_factor_params
wouldn't exist in this case at all -
Kyle K over 5 years@Fire Lancer thank you! I just ran into a situation where I had to conditionally set a base variable to look up associated records using different relationships depending on the model requesting the associated records and this worked perfectly!