ruby on rails 5 server-side CSV validation ERROR - ruby-on-rails

In my lib/csv_validation.rb file I got my validate method:
def self.validate(file, delimiter, columns)
return false unless File.exist?(file)
content = File.read(file, encoding: 'utf-8')
return false unless content.valid_encoding?
content.each_line do |line|
return false if line.count(delimiter) < columns - 1
end
true
end
when I send a CSV file via ajax post request I get the following error:
Started POST "/students/import" for 127.0.0.1 at 2017-12-20 01:03:43 +0100
Processing by StudentsController#import as */*
Parameters: {"file"=>#<ActionDispatch::Http::UploadedFile:0x007fd0a228ca38 #tempfile=#<Tempfile:/tmp/RackMultipart20171220-4516-or6qi3.csv>, #original_filename="students_fail.csv", #content_type="text/csv", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"students_fail.csv\"\r\nContent-Type: text/csv\r\n">}
Completed 500 Internal Server Error in 19ms (ActiveRecord: 0.0ms)
TypeError (can't convert ActionDispatch::Http::UploadedFile to IO (ActionDispatch::Http::UploadedFile#to_io gives Tempfile)):
app/models/student.rb:114:in `exist?'
app/models/student.rb:114:in `import'
app/controllers/students_controller.rb:50:in `import'
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.text.erb (0.4ms)
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.4ms)
Rendering /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.6ms)
Rendered /var/lib/gems/2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (14.4ms)
DEPRECATION WARNING: Accessing mime types via constants is deprecated. Please change `Mime::HTML` to `Mime[:html]`. (called from acceptable_content_type? at /var/lib/gems/2.4.0/gems/web-console-2.3.0/lib/web_console/middleware.rb:58)
I was searching for can't convert ActionDispatch::Http::UploadedFile to IO but I just find something like can't convert ActionDispatch::Http::UploadedFile into String.
I am not sure how to handle this error or where I can find someone with the same problem.
sorry for my bad english and thx for help.

You'll want to use the ActionDispatch::Http::UploadedFile#tempfile method.
Documented here.
So you can call it like this:
File.read(file.tempfile, encoding: 'utf-8')
That will allow the object to transform to an actual file as opposed to an ActionDispatch object.
See this SO Article: Reading in file contents rails

Related

Controller gives wrong number of arguments error when GET request is made

I have written a rails-api with two resources users and books. When I make a GET request for books it works properly, but for users it fails with the following message:
Started GET "/users/" for 127.0.0.1 at 2015-11-18 23:45:52 +0530
Processing by UsersController#index as HTML
User Load (0.5ms) SELECT `users`.* FROM `users`
Completed 500 Internal Server Error in 63ms (ActiveRecord: 4.2ms)
ArgumentError (wrong number of arguments (0 for 1)):
app/controllers/users_controller.rb:8:in `index'
Rendered /Users/me/.rvm/gems/ruby-2.2.3/bundler/gems/rails-35ca78a07c8b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb (17.6ms)
Rendered /Users/me/.rvm/gems/ruby-2.2.3/bundler/gems/rails-35ca78a07c8b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.1ms)
Rendered /Users/me/.rvm/gems/ruby-2.2.3/bundler/gems/rails-35ca78a07c8b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.2ms)
Rendered /Users/me/.rvm/gems/ruby-2.2.3/bundler/gems/rails-35ca78a07c8b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (69.4ms)
Here is the error I get on the browser:
ArgumentError in UsersController#index
wrong number of arguments (0 for 1)
Extracted source (around line #8):
...
# GET /users
def index
#users = User.all
render json: #users # this is line 8
end
...
config/routes.rb
Rails.application.routes.draw do
resources :users
resources :books
end
Any clue on what might be going wrong?
The error was with my model that was being passed to the serializer. I had a column in my database with the name method. method is a rails reserved word (read: ruby-and-rails-reserved-words) which was creating the problem. I renamed my column to registration_method which fixed the issue. Thanks everyone for the help :)
could try render #users.to_json
Is User.all returning any users?

url parameters are not in params

I want to get information from the TwitchTV OAuth API, and the authorization works well, but I can not get the code that Twitch redirects me to.
For example:
http://localhost/?code=noj4n39487fn29fn23v92hr293hnru23v97hre&scope=
This is how Twitch redirects back to my page. In the log of my rails server it also shows the following:
Started GET "/?code=q5yptiyx3cdaep52b7xyqgt3vjpwhg&scope=" for 371.1721.13.179 at 2015-08-22 17:09:26 +0200
Cannot render console from 315.127.134.179! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by HomeController#index as HTML
Parameters: {"code"=>"q5ypti345ferf2rf2efr2erferfe23ff", "scope"=>""}
News Load (0.6ms) SELECT "news".* FROM "news"
Rendered home/index.html.erb within layouts/home (14.7ms)
Completed 200 OK in 124ms (Views: 120.6ms | ActiveRecord: 1.0ms)
But when I try to get params.inspect in the controller, it shows this:
{"controller"=>"oauth", "action"=>"index"}
my controller looks like this:
class OauthController < ApplicationController
def index
redirect_to 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=34n87fn48fn438rzfghb4z8rofg4rg&redirect_uri=http://localhost/'
logger.info params.inspect
end
end
Obviously I changed all the ip's, auth-codes and stuff. My question is, shouldn't params return the parameters since it shows them as parameters (in the first code block) ?
Localhost is local address and 'outworld' API cannot send information back to 'localhost', you have to use http://127.0.0.1 or get a real domain for you development environment.

react-rails with jbuilder doesn't work

I try to use react-rails with jbuilder.
For example, I use this great sample app of react-rails and try to rewrite to use jbuilder as a json response using reference from this part in react-rails.
These are the main rewrite parts:
# app/views/comments/index.html.erb
<%= react_component 'CommentBox', render(template: 'comments/index.json.jbuilder'), {prerender: true} %>
# app/views/comments/index.json.jbuilder
json.presenter do
json.comments(#comments) do |comment|
json.extract! comment, :id, :author
end
json.form do
json.action comments_path
json.csrf_param request_forgery_protection_token
json.csrf_token form_authenticity_token
end
end
json.imgSrc image_path("gundam.jpg")
But I got an following error:
Started GET "/comments" for 127.0.0.1 at 2015-04-07 18:26:40 +0900
Processing by CommentsController#index as HTML
Comment Load (0.9ms) SELECT "comments".* FROM "comments" ORDER BY "comments"."id" DESC LIMIT 5
Rendered comments/index.json.jbuilder (8.4ms)
Rendered comments/index.html.erb within layouts/application (34.6ms)
Completed 500 Internal Server Error in 43ms
ActionView::Template::Error (SyntaxError: Unexpected token o):
app/views/comments/index.html.erb:3:in `_app_views_comments_index_html_erb___3472795088323540071_70123597415980'
Do you have any idea to solve this error?
Thanks in advance.
see full source code:
Use jbuilder but it gets an error · jwako/sample-react-rails-app#508d581
It looks like the unexpected token is raised because the CommentBox component is calling JSON.parse() in getInitialState when this.props.presenter is already a JSON object.
You can fix it by removing JSON.parse() in getInitialState and returning only this.props.presenter.
Here is a related answer on parsing existing JSON objects.

Rails: logger.debug not working inside Model function

I have a bunch of logger.debug statements in my Controller. They currently write the place where all the HTTP requests and everything are displayed in real time on my WEBRick server. However,
when I write logger.debug statements in my Model, they are not written to this same location, additionally they are not to be found in log/development which is the environment I have been working in. It is particularly frustrating because I make the call to the following Model function in a controller that has successfully executed logger.debug statements:
def process_payment
uri = URI('https://demo.myvirtualmerchant.com/VirtualMerchant/processxml.do')
the_xml = SchoolApplication.to_xml(params[:credit_card],
params[:expiration],
params[:cvv2_cvc2],
params[:amount],
params[:name])
logger.debug(the_xml)
the_xml = the_xml.to_s
my_hash = {'xmldata' => the_xml}
logger.debug(the_xml)
response = Net::HTTP.post_form(uri, my_hash)
#response_var = response
if response.response == 0
render 'receipt'
else
render 'card_Error'
end
end
the two logger.debug statements in this controller method are written to what I suppose is STDOUT? In any case I see them in the location which displays the following kind of information:
Rendered web_applications/card_Error.html.erb within layouts/application (1.7ms)
Completed 200 OK in 433ms (Views: 13.1ms | ActiveRecord: 0.0ms)
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-07-22 11:32:02 -0700
In the above Controller method when I make the call to SchoolApplication.to_xml,
it does not execute the corresponding logger.debug() statements (or maybe it writes them
to a different place? That wouldn't make sense but I am also a n00b, clearly) that are in
to_xml Model method as shown below:
def self.to_xml(number,expiration,cvv,amount, name)
xml = ::Builder::XmlMarkup.new
logger.debug(number)
logger.debug(name)
xml.txn {
xml.ssl_test_mode false
xml.ssl_card_number number
xml.ssl_amount amount
xml.ssl_cvv2cvc2_indicator cvv
xml.ssl_first_name name
xml.ssl_show_form false
xml.ssl_exp_date '25/34'
xml.ssl_track_data
xml.ssl_result_format HTML
xml.ssl_receipt_link_method
xml.ssl_receipt_link_url "#{Rails.root}" + '/receipts/receive'
xml.ssl_receipt_link_text
}
xml
end
N.B. I know that the above to_xml is being successfully called and returned from as the rest of my controller method which calls this model function executes without error.
Here is the output after I go to the route which calls the process_payment controller function:
Started POST "/application/pay" for 127.0.0.1 at 2014-07-22 12:13:40 -0700
Processing by WebApplicationsController#process_payment as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pJD6Q7qJPXFNaGEczv5kTSKBC5TcG8lqhOuLNjw9UrY=", "web_application"=>{"first_name"=>"bob", "last_name"=>"job", "card_number"=>"41111111111111", "expiration_date"=>"232", "cvv2_cvc2"=>"232"}, "commit"=>"Save Web application"}
<txn><ssl_merchant_id/><ssl_user_id/><ssl_ssl_pin/><ssl_test_mode>false</ssl_test_mode> <ssl_card_number/><ssl_amount/><ssl_cvv2cvc2_indicator/><ssl_first_name/ ><ssl_show_form>false</ssl_show_form><ssl_exp_date>25/34</ssl_exp_date><ssl_track_data/><ssl_result_format>HTML</ssl_result_format><ssl_receipt_link_method/><ssl_receipt_link_url> <ssl_receipt_link_text/></txn><to_s/>
<txn><ssl_merchant_id/><ssl_user_id/><ssl_ssl_pin/><ssl_test_mode>false</ssl_test_mode> <ssl_card_number/><ssl_amount/><ssl_cvv2cvc2_indicator/><ssl_first_name/><ssl_show_form>false</ssl_show_form><ssl_exp_date>25/34</ssl_exp_date><ssl_track_data/><ssl_result_format>HTML</ssl_result_format><ssl_receipt_link_method/>
Rendered web_applications/card_Error.html.erb within layouts/application (3.8ms)
Completed 200 OK in 742ms (Views: 22.6ms | ActiveRecord: 0.0ms)
which is equivalent to what was written in development.log

send_file not working - Ruby on Rails

I have this action here :
def download
send_file 'C:/Sites/solver/public/test.zip'
end
When I execute it from my html nothing happens and nothing is downloaded.
But here is the log it produce :
Started POST "/ssh/download" for 127.0.0.1 at 2014-04-03 11:06:17 -0400
Processing by SshController#download as */*
Sent file C:/Sites/solver/public/test.zip (0.0ms)
Completed 200 OK in 5ms (ActiveRecord: 0.0ms)
Anyone can help me understand what is missing ?
Thank you!
In your view, add a download option, eg:
link_to 'Download', download_path(id), download: "file"

Resources