react-rails with jbuilder doesn't work - ruby-on-rails

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.

Related

ruby on rails 5 server-side CSV validation ERROR

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

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?

Method not allowed rails

I am making an ajax post call to a controller. My Ajax call is:
$.ajax({
type:'POST',
url:'/chefUI/configure/save_roles',
data:{ app_name: appname, role_list: role_list},...});
My Routes file is:
scope "/chefUI" do
post '/configure/save_roles', to: 'admin#update_app_roles'
end
And my controller has:
def update_app_roles
begin
application_name = params["app_name"]
puts application_name
role_name_list = params["role_list"]
puts role_name_list
if application_name and !role_name_list.empty?
...
And I am getting a 405 Method Not Allowed response. I'm not sure what are the reasons this might happen. Could someone help me figure out what I'm missing here? I don't why my post request is not even reaching my controller.
Update:
Log file
Started GET "/chefUI/configure/app_roles?app_name=MFRH" for 127.0.0.1 at 2015-07-24 15:08:51 +0530 Processing by AdminController#app_roles as */* Parameters: {"app_name"=>"MFRH"} [1m[35mUser Load (1.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."username" = $1 LIMIT 1 [["username", "an9v0s7"]] [1m[36mApplication Load (2.0ms)[0m [1mSELECT "applications".* FROM "applications" WHERE (lower(app_name) = 'mfrh') ORDER BY "applications"."id" ASC LIMIT 1[0m [1m[35mRole Load (1.0ms)[0m SELECT "roles".* FROM "roles" INNER JOIN "application_roles" ON "roles"."id" = "application_roles"."role_id" WHERE "application_roles"."application_id" = $1 ORDER BY roles.name ASC [["application_id", 1]] Completed 200 OK in 217ms (Views: 0.0ms | ActiveRecord: 5.0ms)
Started POST "/chefUI/configure/save_roles" for 127.0.0.1 at 2015-07-24 15:08:57 +0530
Another Update:
I just found out that I'm getting that response for all my post requests. They were all working before, I created a bunch on new models and suddenly none of them are working.
This problem is a bit deeper than thought before.
Rails does not like when a route path and the asset directory are in the same subdirectory.
When making a post request, you will get method not allowed. The problem is there can be no overlap with paths and the asset directory. The problem is specifically with POST requests in that path. I am assuming somewhere in rails, they must have disabled all non-GET requests for the assets directory.
scope "/chefUI" do
post '/configure/save_roles', to: 'admin#update_app_roles'
end
config.assets.prefix="/chefUI/assets"
^ You need this part so they don't overlap.
In this very simple app below, you will get a method not allowed error. Because the path /welcome is being used for a route and for an asset prefix.
File: config/environment/development.rb
config.assets.prefix = '/welcome'
File: config/routes.rb
resources :welcomes, path: 'welcomes', only: ['index', 'create']
File: app/controllers/welcomes_controller.rb
class WelcomesController < ApplicationController
def index
#welcome = 'hello';
end
def create
#welcome = 'world';
end
end
File: app/views/welcomes/index.html.rb
<%= form_for(#welcome) do |f| %>
<%= f.submit 'Submit' %>
<% end %>
File: app/views/welcomes/create.html.rb
<h1>Welcomes#create</h1>
<p>Find me in app/views/welcomes/create.html.erb</p>
I removed the below line in application.rb and the issue got resolved. config.assets.prefix="/chefUI"
I don't understand what config.assets.prefix has to do with POST requests, but this resolved my issue.
Would love to understand the reason though.

Select_Tag not working in rails?

Here is my code for select_tag
<%= select_tag :tp, options_for_select([["movable",1],["fixed",2]]), :prompt => "select type of asset" %>
it works if i replace by:
<%= f.text_area :tp %>
If this in not enough i will give more code as you desire:
here is the log after i use select_tag
Started POST "/assets" for 127.0.0.1 at 2014-03-07 23:40:34 +0530
Processing by AssetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Gib6rSODjXgXLZ9+5sDcq0ZatkA7144hU+Em2X7KONU=", "asset"=>{"name"=>"", "location"=>"", "cost"=>""}, "tp"=>"1","commit"=>"Save"}
(1.0ms) BEGIN
(1.0ms) ROLLBACK
Redirected to http://localhost:3000new
Completed 302 Found in 5ms (ActiveRecord: 2.0ms)
[2014-03-07 23:40:34] ERROR URI::InvalidURIError: the scheme http does not accept registry part: localhost:3000new (or bad hostname?)
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/uri/generic.rb:1203:in `rescue in merge'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/uri/generic.rb:1200:in `merge'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/httpresponse.rb:275:in `setup_header'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/httpresponse.rb:205:in `send_response'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/httpserver.rb:110:in'run'
F:/RailsInstaller/Ruby2.0.0/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
Started GET "/assets/logo.png" for 127.0.0.1 at 2014-03-07 23:40:36 +0530
Error after changing to `real_assets_path
Started GET "/real_assets/new" for 127.0.0.1 at 2014-03-09 13:56:47 +0530
ActiveRecord::SchemaMigrationLoad(1.0ms)SELECT"schema_migrations".* FROM"schema_migrations"
Processing by AssetsController#new as HTML
Rendered assets/new.html.erb within layouts/application (30.0ms)
Completed 500 Internal Server Error in 98ms
ActionView::Template::Error (undefined method `assets_path' for #<# <Class:0x545bb78>:0x545aeb8>):
1: <div class = "container">
2: <div id = "assetnew">
3: <%= form_for(#asset) do |f| %>
4: <center><h1>Add Asset</h1></center>
5: <div class = "well">
6: <a class ="red">
app/views/assets/new.html.erb:3:in`_app_views_assets_new_html_erb___457532114_11608392'
Rendered
F:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered
F:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered
F:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (18.0ms)
Assets
This is the error Rails is returning:
ERROR URI::InvalidURIError: the scheme http does not accept registry part: localhost:3000new (or bad hostname?)
Without seeing your form, it seems you've got an issue with calling your resource /assets (as mentioned in the comments)
Basically, Rails treats the assets pipeline as a base directory - localhost:3000/your_asset_file.png -- it looks like this is what's happening here
Because your app is referencing /assets, I would surmise it's confusing it with the assets dir. Try doing this:
#config/routes.rb
resources :assets, as: "real_assets", path: "real_assets" #-> real_assets_path - /real_assets
Select
The select problem is likely caused by your assets path problem
select_tag is a standalone helper method (doesn't need any FormBuilder to help it). This means you should be able to just use it in an .html.erb file without any problems
The syntax for the select looks okay, so I'd recommend if you get your assets path fixed, you should be able to use it

apn_on_rails breaking view helpers on rails 2.3.8?

I am developing a rails application which should send push notifications to iOS devices. I am using apn_on_rails gem. Everything works fine in the rails console. However when I run the server, I get undefined method errors for all the basic view methods such as content_for or form_tag etc:
When I take require 'apn_on_rails' from my development.rb out, the views work again, but of course without push notifications.
Here is an example trace:
Processing DashboardController#index (for 127.0.0.1 at 2011-02-27 13:55:59) [GET]
User Load (0.2ms) SELECT * FROM "users" WHERE ("users"."id" = 1)
CACHE (0.0ms) SELECT * FROM "users" WHERE ("users"."id" = 1)
Rendering template within layouts/dashboard
Rendering dashboard/index
ActionView::TemplateError (undefined method `content_for' for #<ActionView::Base:0x103343970>) on line #1 of app/views/dashboard/index.html.erb:
1: <% content_for :header do %>
2: <%= render :partial => "header", :locals => {:title => "Dashboard"} %>
3: <% end %>
app/views/dashboard/index.html.erb:1
app/controllers/dashboard_controller.rb:6:in `index'
Rendered rescues/_trace (28.5ms)
Processing ApplicationController#index (for 127.0.0.1 at 2011-02-27 13:55:59) [GET]
ActionView::TemplateError (undefined method `debug' for #<ActionView::Base:0x103343970>) in /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/templates/rescues/_request_and_response.erb:
Rendered rescues/_trace (24.0ms)
/!\ FAILSAFE /!\ Sun Feb 27 13:55:59 +0100 2011
Status: 500 Internal Server Error
ActionView::TemplateError (undefined method `debug' for #<ActionView::Base:0x1031eaad8>) in /Library/Ruby/Gems/1.8/gems/actionpack-2.3.8/lib/action_controller/templates/rescues/_request_and_response.erb:
In /library/ruby/gems/1.8/gems/actionpack-2.3.8/lib/action_controller/templates/rescues/_request_and_response.erb
Thanks for any help...
It is not evident whether you call config.gem 'apn_on_rails' - it sounds more like you are require:ing the library, which probably is something you should not do at this point: the point of environment setup.
Have the config.gem things in your environment setup (i.e. development.rb), but make eventual requires happen later (->in the controller / model / helper in question).

Resources