skwidbreth skwidbreth - 5 months ago 9
JSON Question

Rails - submitting JSONs to database from controller

I am working on a Rails app, and I am attempting to insert attributes from JSONs as database entries. I'm running into a problem, though, and would appreciate some guidance.

I've been able to jam a few things together and come up with something that sort of works...

def create
@report_group = Array.new

@report_group.push({location:"home", comments:"Hello, database!"}, {location:"away", comments:"Goodbye, database!"})

@report_group.each do |x|

@new_report = Report.new(x)
@new_report.user_id = current_user.id

@new_report.save
end
end

private
def report_params(params)
params.permit(:user_id,:location,:comments)
end


This is a good first step - this commits two entries to my database, one for each of the hashes pushed into @report_group, but it is suffering from a problem - the create action does not reference the
report_params
whitelist.

I have built several Rails apps where entries are submitted one at a time via the standard Rails form helpers, but I have never done it with multiple JSONs like this before. Trying out the syntax I'd use in a typical form helper situation

@new_report = Report.new(report_params(x))


throws the expectable error
undefined method permit' for #<Hash:0x007f966b35e270>
but I am not sure what else to do here.

EDIT TO SHOW SOLUTION
Big thanks to @oreoluwa for pointing me in the right direction. Here's the solution that I came up with.

def create
@report_group = Array.new

@report_group.push({location:"home", comments:"Hello, database!"}, {location:"away", comments:"Goodbye, database!"})

@report_group.each do |x|

hash = ActionController::Parameters.new(x)

@new_report = Report.new(report_params(hash))
@new_report.user_id = current_user.id

@new_report.save
end
end

private
def report_params(params)
params.permit(:user_id,:location,:comments)
end

Answer

You're getting the error because a Hash is not the same as an ActionController::Parameters. In order to use the permit method with your Hash you may need to first convert it to ActionController::Parameters, as such:

hash = {location:"home", comments:"Hello, database!"}
parameter = ActionController::Parameters.new(hash)
parameter.permit(:user_id,:location,:comments)

I don't know if that is what you're looking for, but I thought to point you in the right direction.