NoMethodError (undefined method `permit' for #<Array:0x007f51c020bd18> - ruby-on-rails-5

I am getting this error and using Rails 5.
NoMethodError (undefined method permit' for #<Array:0x007f51cf4dc948>
app/controllers/traumas_controller.rb:99:intrauma_params'
app/controllers/traumas_controller.rb:25:in `create_multiple'
Controller params are as below.
Started POST "/traumas/create_multiple" for 127.0.0.1 at 2016-10-04
20:09:36 +0530 Processing by TraumasController#create_multiple as JS
Parameters: {"utf8"=>"✓", "fields"=>[{"contusions"=>"1", "burns"=>"",
"at_scene"=>"At Scene", "emergency_detail_id"=>"96",
"trauma_region"=>"Head-Back"}], "commit"=>"Submit"}
I am trying to create record as below in controller:
def create_multiple
trauma_params
params[:fields].each do |values|
u = Trauma.create(values)
end
end
def trauma_params
params.require(:fields).permit(:fields => [])
end
Please help me to resolve this issue.
Thanks in advance.
Kiran.

Parameters:
{"fields"=>[{"contusions"=>"1", "burns"=>"", "at_scene"=>"At Scene", "emergency_detail_id"=>"96", "trauma_region"=>"Head-Back"}]}
Safelist array of objects, with the "fields" attribute required:
def trauma_params
params.permit(fields: [
:contusions,
:burns,
:at_scene,
:emergency_detail_id,
:trauma_region
])
.require(:fields)
end
Source: https://edgeguides.rubyonrails.org/action_controller_overview.html#nested-parameters

I resolved it by referring this (https://github.com/rails/strong_parameters/issues/140) github issue.
EDIT
For parameters like the following (which are in Array):
Parameters: {"fields"=>[{"contusions"=>"1", "burns"=>"",
"at_scene"=>"At Scene", "emergency_detail_id"=>"96",
"trauma_region"=>"Head-Back"}], "commit"=>"Submit"}
We can do:
def trauma_params
params.require(:fields).map do |p|
ActionController::Parameters.new(p).permit(
:contusions,
:burns,
:at_scene,
:emergency_detail_id,
:trauma_region
)
end
end

Related

Mailer function Ruby on Rails issue

I am trying compile a function with user id, but not working out. Tried different ways but getting nil as response in my production logs.
Any help is welcome
def function(user)
attachments['example.pdf'] = File.read("public/#{#user.id}_file.pdf")
#user = user
mail :subject => 'example', to: user.email, from: 'invoice#domain.com', track_opens: true
end
Log:
D, [2019-07-08T10:51:56.838759 #64733] DEBUG -- :
TestMailer#send_sub_month: processed outbound mail in 1.1ms I,
[2019-07-08T10:51:56.839003 #64733] INFO -- : Completed 500 Internal
Server Error in 5ms (ActiveRecord: 0.4ms) F,
[2019-07-08T10:51:56.839615 #64733] FATAL -- : F,
[2019-07-08T10:51:56.839671 #64733] FATAL -- : NoMethodError
(undefined method 'id' for nil:NilClass): F,
[2019-07-08T10:51:56.839710 #64733] FATAL -- : F,
[2019-07-08T10:51:56.839750 #64733] FATAL -- :
app/mailers/test_mailer.rb:90:in `send_sub_month'
The logs say that you are trying to access the id attribute of an empty object.
NoMethodError (undefined method id' for nil:NilClass)
You have a string where the user is used is higher than the string where the user is defined
Try this:
def function(user)
#user = user
attachments['example.pdf'] = File.read("public/#{#user.id}_file.pdf")
mail :subject => 'example', to: user.email, from: 'invoice#domain.com', track_opens: true
end
Updated.
If you pass a user as an argument to a function, then it makes no sense to create a variable for it.
def function(user)
attachments['example.pdf'] = File.read("public/#{user.id}_file.pdf")
mail :subject => 'example', to: user.email, from: 'invoice#domain.com', track_opens: true
end

NoMethodError (undefined method `permit' for "note_id":String):

I'm having issues with an API in Rails4/mongoid application. I need to manipulate the data with a python 3 script through an API but I'm getting
NoMethodError (undefined method `permit' for "note_id":String):
error when I try to submit the request.
My python codes looks like this
import requests
import json
url = 'http://0.0.0.0:3000/api/v1/note_proc_logs.json'
payload = {'note_proc_log' : { 'note_id' : '120904'}}
head = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxx"}
r = requests.post(url, payload, headers=head)
The API controler
module Api
module V1
# This class does not inherit from ApplicationController like the rest to skip Devise authentication
class NoteProcLogsController < ActionController::Base
before_filter :restrict_access if Rails.env.development? == false
respond_to :json
def create
Rails.logger.warn "note_proc_log_params: #{params}" if Rails.env.development?
#note_proc_log = NoteProcLog.new(note_proc_log_params)
respond_to do |format|
if #note_proc_log.save
format.json { render :show, status: :created, location: #note_proc_log }
else
format.json { render json: #note_proc_log.errors, status: :unprocessable_entity }
end
end
end
private
def restrict_access
authenticate_or_request_with_http_token do |token, options|
ApiKey.where(access_token: token).exists?
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def note_proc_log_params
params.require(:note_proc_log).permit(:note_id)
end
end
end
end
I saw few question with the same error but couldn't find a solution to my problem.
Any help would be greatly appreciated.
UPDATE:
Rails.logger.warn "note_proc_log_params: #{params}" if Rails.env.development?
gives me
W, [2016-07-25T15:10:38.362848 #48352] WARN -- : params: {"note_proc_log"=>"note_id", "format"=>"json", "controller"=>"api/v1/note_proc_logs", "action"=>"create"}
The problem was in the python script. A simple python dictionary is ok as payload but nested ones appear not to be.
My final python script look like this
import requests
import json
url = 'http://0.0.0.0:3000/api/v1/note_proc_logs.json'
payload='note_proc_log[chip_id]=120904&note_proc_log[test_timestamp]=2016-07-19T13:24:49'
head = {"Authorization":"Token token=xxxxxxxxxxxxxxxxxxxx"}
r = requests.post(url=url, data=payload, headers=head)
On Rails side everything will be treated as string so no need for adding additional quotation marks, even for strings with spaces, parent attribute has to be specified for each child attribute and elements separated with &.
This is what works for me, it would be interesting to know if there are other/better ways to do it, in particular how to include an Array of values.

Paperclip and Phusion Passenger NoHandlerError

I followed this guide to get drag and drop file uploads through AJAX: http://dannemanne.com/posts/drag-n-drop_upload_that_works_with_ror_and_paperclip
Everything was working fine on my development environment with WebBrick but if I deploy to PhusionPassenger then I get:
Paperclip::AdapterRegistry::NoHandlerError (No handler found for #<PhusionPassenger::Utils::RewindableInput:0x000000041aef38 #io=#<PhusionPassen...
I'm using this in my controller:
before_filter :parse_raw_upload, :only => :bulk_submissions
def bulk_submissions
...
#submission = Submission.create!(url: "", file: #raw_file, description: "Please edit this description", work_type: "other", date_completed: DateTime.now.to_date)
...
end
private
def parse_raw_upload
if env['HTTP_X_FILE_UPLOAD'] == 'true'
#raw_file = env['rack.input']
#raw_file.class.class_eval { attr_accessor :original_filename, :content_type }
#raw_file.original_filename = env['HTTP_X_FILE_NAME']
#raw_file.content_type = env['HTTP_X_MIME_TYPE']
end
end
Looking at the request itself all the headers are set (X_MIME_TYPE, X_FILE_NAME) etc.
Any ideas?
Thanks in advance!
The example you're cribbing from expects the file stream to be a StringIO object, but Passenger is giving you a PhusionPassenger::Utils::RewindableInput object instead.
Fortunately, a RewindableInput is duckalike to StringIO for this case, so Paperclip's StringioAdapter can be used to wrap your upload stream.
Inside the if block in your parse_raw_upload, at the end, do:
if #raw_file.class.name == 'PhusionPassenger::Utils::RewindableInput'
#raw_file = Paperclip::StringioAdapter.new(#raw_file)
end

Weird error when delivering mail : undefined method `index' for 2011-09-09 22:15:28 +0200:Time

When I deliver emails I get this weird error :
Failure/Error: publication = FactoryGirl.create(:publication, :author => author)
NoMethodError:
undefined method `index' for 2011-09-09 22:15:28 +0200:Time
And the stack trace is not of any help.
Any idea ?
Very simple, you should NOT use :
default :sent_on => Time.now
in your mailer class.
Was tricky though :)
I've got this error when I passed (mistakenly) the :headers parameter to
the mail method. After removing :headers (and using the headers method instead)
it worked.

Can't access image_tag from helper module

I would like to test the following helper module function:
module UploadsHelper
def custom_img_tag(upload, width, height, id)
if width > Upload::MAX_CROP_WIDTH
image_tag(upload.photo.url(:original), :id => "box", :width => Upload::MAX_CROP_WIDTH, :height => (height*Upload::MAX_CROP_WIDTH/width).to_i)
else
image_tag(upload.photo.url(:original), :id => "box")
end
end
end
However when I run the following test:
describe UploadsController do
include UploadsHelper
describe "custom_img_tag(upload, width, height, id)" do
before(:each) do
#upload = Factory(:upload)
geo = Paperclip::Geometry.from_file(#upload.photo.to_file(:original))
#width = geo.width
#height = geo.height
end
it "should return the original image tag for an image that is not wider than MAX_CROP_WIDTH" do
#custom_img_tag(#upload,#width, #heigth, "cropbox" ).should == '<img id="cropbox" width="500" height="375" src="/system/photos/10/original/avatar.jpg?1311044917" alt="Avatar" style="display: none;">'
end
end
I get the following error:
Failure/Error: custom_img_tag(#upload,#width, #heigth, "cropbox" ).should == '<img id="cropbox" width="500" height="375" src="/system/photos/10/original/avatar.jpg?1311044917" alt="Avatar" style="display: none;">'
NoMethodError:
You have a nil object when you didn't expect it!
Why do I get this error and how can I test this method?
Update:
I added the following to the spec test file:
include ActionView::Helpers
Which produces the following error:
NameError:
undefined local variable or method `config' for #<RSpec
How can I get rid of this error and what is the cause?
Thanks for any assistance.
I also got hit with the error working with Rails 3.1 RC
NameError:
undefined local variable or method `config'
Some Rails source tracing and I discovered the missing include ActionView::AssetPaths.
include ActionView::AssetPaths
include ActionView::Helpers::AssetTagHelper
Well, I don't know why this would be, but my guess is that for some reason ActionView::Helpers must not be loaded in this spec. Try including ActionView::Helpers and see if that fixes it... The issue (from what you're reporting) is that when your custom_img_tag method gets called it isn't able to call image_tag for some reason.