This is my code
def create
@p_site = PSite.find(params.require(:plan_for).first[0])
authorize @p_site, :c_s?
if @p_site.save
redirect_to :root, notice: "successfully added"
else
render :new
end
end
When I'm running it I get undefined method 'first' for <ActionController::Parameters:0x00005623c4d56f68>
My params[:plan_for] looks like this:
#<ActionController::Parameters {"82"=>"annual"} permitted: false>
I need to get the value of 82 and find in PSite. How can i do this?
CodePudding user response:
Params is a Hash here and not an Array. The way a Hash is structured is in key value pairs. For example:
my_hash = { key: "Some Value" }
mz_hash[:key] #=> "Some Value"
So the first thing I am wondering is why you have 82 as the key here? If its an id I would restructure that to be something like this: { id: 82, recurrence: "annual" }
Specifically for your case:
params[:plan_for]["82"] #=> "annual"
params.require(:plan_for)["82"] #=> "annual"
# OR very dirty
params[:plan_for].values.first #=> "annual"
params[:plan_for].keys.first #=> "82"
You might see how the first two lines above wont work unless "82" is the key for all your params (in which case name it better!) and the latter might be a dirty solution for your code right now but also not something I would recommend.
Check out the documentation for ruby hashes
CodePudding user response:
I have first permitted my params and then converted it to hash and accessed it by using first[0].
@pp = params.require(:plan_for).permit!.to_h
@p_site = PractitionerSite.find(@pp.first[0])