Saturday, July 9, 2016

no implicit conversion of Symbol into Integer - working with param from URL | Fixed issues

no implicit conversion of Symbol into Integer - working with param from URL | Fixed issues


no implicit conversion of Symbol into Integer - working with param from URL

Posted: 09 Jul 2016 07:12 AM PDT

Trying to convert a param included in the the URL into an integer, to operate with it within a Controller - The format of the URL is like http://localhost:3000/charges?data=149&email=email@gmail.com

The charges_controller.rb looks like:

class ChargesController < ApplicationController    protect_from_forgery with: :null_session      def new    end        def create        @amount = {}      @amount = params [:**data**][:email].map(&:to_i)      @amount.save        customer = Stripe::Customer.create(        :email => params[:stripeEmail],        :source  => params[:stripeToken]      )        charge = Stripe::Charge.create(        :customer    => customer.id,        :amount      =>  @amount,        :description => 'Rails Stripe customer',        :currency    => 'eur'      )      rescue Stripe::CardError => e      flash[:error] = e.message      redirect_to new_charge_path    end    end  

And the params I can see in better_errors screen detect already the 'data' amount:

{"stripeToken"=>"asdfasdf", "stripeTokenType"=>"card", "stripeEmail"=>"email@gmail.com", **"data"=>"149"**, "email"=>"email@gmail.com", "action"=>"create", "controller"=>"charges"}  

In the live shell in better errors if I do params[:data].to_i it returns 149, but if I include it directly in the controller like:

@amount = {}  @amount = params [:data].to_i[:email]  @amount.save  

it returns undefined method `to_i' for [:data]:Array

Tried also mapping them like: @amount = params [:data][:email].map(&:to_i),same result "no implicit conversion of Symbol into Integer"

SocketError at /sidekiq/ getaddrinfo: nodename nor servname provided, or not known

Posted: 09 Jul 2016 07:01 AM PDT

I'm a novice Rails dev building an app connected to redis + sidekiq. I must have some configuration error, but I'm not sure what exactly it is. Below, I'll write about what exactly confuses me here:

Upon running rails s, I get the following error:

2016-07-09 08:55:46 - SocketError - getaddrinfo: nodename nor servname provided, or not known:  /Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:177:in `getaddrinfo'  /Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:177:in `connect'  /Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/connection/ruby.rb:260:in `connect'  /Users/rohitrekhi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/redis-3.3.0/lib/redis/client.rb:336:in `establish_connection'  

So I figured it must be a redis connection error. When I ping redis to see if connection goes through, it shows the following:

$ redis-cli ping  => PONG  

So if the redis connection goes through, maybe it's a Sidekiq issue?

I implemented the Sidekiq web interface via Sinatra, and got the following error when I tried to view it:

SocketError at /sidekiq/  getaddrinfo: nodename nor servname provided, or not known  

So now I'm guessing the error is actually via Sidekiq, but I'm not sure where I dropped the ball via configurations on the host/server/sockets. Any ideas what exactly is causing this and if it's an error with Sidekiq or redis?

This is my initializer file for sidekiq in config/initializers/sidekiq.rb:

Sidekiq.configure_server do |config|  config.redis = { url: 'redis://redis.example.com:6379/12', network_timeout: 5 }  end    Sidekiq.configure_client do |config|    config.redis = { url: 'redis://redis.example.com:6379/12', network_timeout: 5 }  end  

And this is my config/initializer/redis.rb:

$redis = Redis.new(:host => 'localhost', :port => 6379)  

I've also opened three terminal windows turning on the redis server, sidekiq, and my rails server.

Thanks in advance!

ActiveRecord feature proposal: find_unique_by

Posted: 09 Jul 2016 06:51 AM PDT

I have sent the following message to the Rails Core mailing list and got no reply. I assume there was no interest in this feature and/or there is something wrong with the following code. If you can provide any feedback, I'd appreciate it very much. I'm not asking a specific question, I'm asking for your opinion on the following feature proposal and the suggested implementation.

--

I used MongoDB before PostreSQL with an ODM called MongoEngine, which has a method for retrieving single results from the DB. It is similar to ActiveRecord find_by! as it raises an exception if no matching records are found. The difference is, it also raises an exception if more than one record matched the query. I've been looking for a similar feature in ActiveRecord but haven't found any so far.

I'm currently using the following workaround, which works with chained where methods,

def ensure_unique    # Ensures an Active Record query returns a *single* record, or raise exception    # Usage: MyModel.where(foo: 'bar').where(baz: 'qux).ensure_unique    if self.many?      raise ActiveRecord::RecordNotUnique, 'More than one record matched criteria. A single match was expected.'    elsif self.empty?      raise ActiveRecord::RecordNotFound, 'No matching records were found. A single match was expected.'    else      # The where method always returns a collection, even when only one record is found.      # We want to return a single item.      return self.first    end  end  

It could also be implemented as a query method (such as find_by!). However, I'd have to look further into it and find a way to support queries involving "AND" logic, such as chaining multiple where methods.

def find_unique_by!(*args)    # Ensures an Active Record query returns a *single* record, or raise exception    # Usage: MyModel.find_unique_by(foo: 'bar')    result = where(*args)    if result.many?      raise ActiveRecord::RecordNotUnique, 'More than one record matched criteria. A single match was expected.'    elsif result.empty?      raise ActiveRecord::RecordNotFound, 'No matching records were found. A single match was expected.'    else      return result.first    end  end  

One use case would be scenarios where you don't have control over the data being inserted in the database (you are working with a legacy DB or a DB managed outside your organization), so you are unable to ensure records are unique.

Any feedback will be greatly appreciated.

Rails - Update Counter Variable when a user shows up as a search result

Posted: 09 Jul 2016 06:33 AM PDT

When searching for students and showing results, I want to be able to update a field in the student_metric table to show how many times a student has shown up in search results.

However, every time i run the show routine i get a undefined method `id' for nil:NilClass. Why wont it find the link between the search_student and student_metric table?

searches controller

def show      @search = current_user.searches.find_by(id: params[:id])      @search.search_students.each do |c|          c.student_metric.searchinclusions += 1      end  end  

search model

class Search < ActiveRecord::Base     belongs_to :user        def search_students          students = StudentProfile.all          students = students.where(["name LIKE ?", "%#{name}%"]) if name.present?      return students      end  end  

student_profile model

class StudentProfile < ActiveRecord::Base     has_one :student_metric, dependent: :destroy    belongs_to :user  end  

student_metric model

class StudentMetric < ActiveRecord::Base    belongs_to :user    belongs_to :student_profile  end  

How does one use the new "rails new myapp --api" with a client-side JavaScript framework?

Posted: 09 Jul 2016 06:25 AM PDT

I apologize if this is a stupid question, but I don't understand the fundamentals of using JSON in accordance with a JavaScript framework in Rails 5.0:

Rails is not only a great choice when you want to build a full-stack application that uses server-side rendering of HTML templates, but also a great companion for the new crop of client-side JavaScript or native applications that just needs the backend to speak JSON. We've made this even clearer now with the new –api mode. If you create a new Rails application using rails new backend --api, you'll get a slimmed down skeleton and configuration that assumes you'll be working with JSON, not HTML.

React seems to be favored by many, so I want to learn how to use it with a Rails backend. To build the hashes I'm leaning toward using Jbuilder.

My main confusion is how to build a layout without an .html.erb view. If I only have two files, one .json.jbuilder, one .js.jsx — how do I call the React components? Or does every controller method need three corresponding views? Or am I just missing the point of --api entirely?

Rails-ShareTribe. Error on npm install (ubuntu 16.04)

Posted: 09 Jul 2016 05:26 AM PDT

I'm very beginner on Ruby and Ruby on Rails and i just managed to install RonR my server. My problem is, when i try to install a platform called ShareTribe, although everything went just fine until bunde install , npm install came with this error:

npm ERR! Linux 4.4.0-21-generic  npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install"  npm ERR! node v4.4.7  npm ERR! npm  v2.15.8  npm ERR! code EBADPLATFORM    npm ERR! notsup Unsupported  npm ERR! notsup Not compatible with your operating system or architecture: fsevents@1.0.12  npm ERR! notsup Valid OS:    darwin  npm ERR! notsup Valid Arch:  any  npm ERR! notsup Actual OS:   linux  npm ERR! notsup Actual Arch: x64    npm ERR! Please include the following file with any support request:  npm ERR!     /home/srv/rails/sharetribe/client/npm-debug.log    npm ERR! Linux 4.4.0-21-generic  npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install"  npm ERR! node v4.4.7  npm ERR! npm  v2.15.8  npm ERR! code ELIFECYCLE  npm ERR! @ postinstall: `cd client && npm install`  npm ERR! Exit status 1  npm ERR!   npm ERR! Failed at the @ postinstall script 'cd client && npm install'.  npm ERR! This is most likely a problem with the  package,  npm ERR! not with npm itself.  npm ERR! Tell the author that this fails on your system:  npm ERR!     cd client && npm install  npm ERR! You can get information on how to open an issue for this project with:  npm ERR!     npm bugs   npm ERR! Or if that isn't available, you can get their info via:  npm ERR!   npm ERR!     npm owner ls   npm ERR! There is likely additional logging output above.    npm ERR! Please include the following file with any support request:  npm ERR!     /home/srv/rails/sharetribe/npm-debug.log`  

What i realized is that My os causes that (Darwin aka. Mac OSX is the valid os)

Is my guess right? If yes, is there any way to install the platform on Ubuntu? If not, how can i correct this error?

Thank you in advance!

What's the database.yml configuration for using Rails with RethinkDB?

Posted: 09 Jul 2016 04:02 AM PDT

I am trying to dive into RethinkDB with Rails and followed the steps until here: https://rethinkdb.com/docs/rails/

How do I configure the database adapter for RethinkDB though?

Can I have two addresses for the same heroku application?

Posted: 09 Jul 2016 04:46 AM PDT

I already have a Rails 4 application and everything is working fine. I want to know if I can have another heroku address, that will redirect to this same app. Please enlighten if it is possible and how so.

Flexible CMS for custom Web-Project

Posted: 09 Jul 2016 02:53 AM PDT

I am starting new project, and I am hesitating between choosing correct CMS and underlying technology.

I will use item as an abstract term, it is something like an order.

My project is not standard blog or e-commerce site. It will have custom features like map of items, live tracking of items, notification about new item.

  1. Live tracking of items on the map
  2. List of items with autoupdate when new item is added
  3. User personal account with the history of items, list current items.
  4. Feedback system
  5. User roles
  6. Items priorities

It would be easy to create using only framework, but in my case I need to have admin panel to control items, and of course security should be taken into consideration. Because reinventing the wheel will lead to security issues.

I have used some CMS but they seem unsuitable for my goals.

And what about language, I used PHP in a lot of projects, once used Ruby On Rails, Ruby is greatly structured language, but as far as I know it has performance issue comparing with PHP

Please suggest the right technology or at least share you experience of using flexible CMS.

Font-Awesome-Rails CSS spinner not working in Safari

Posted: 09 Jul 2016 05:55 AM PDT

I'm using the font-awesome-rails gem to show a css spinner when the submit button of a form_for is clicked. The spinner works perfectly in Chrome and Firefox but doesn't appear in Safari. I'm on OSX El Capitan 10.11.15 and hosting on Heroku. I'm also using Bootstrap 3.

My submit button looks like this:

<%= f.submit "Save Changes", class: "btn btn-default", data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Saving Changes..."} %>  

wrong number of arguments (given 2, expected 0..1) while importing in Rails

Posted: 09 Jul 2016 04:13 AM PDT

I am facing this error while trying to import the file:

ArgumentError - wrong number of arguments (given 2, expected 0..1):    bartt-ssl_requirement (1.4.2) lib/url_for.rb:9:in `url_for_with_secure_option'    actionpack (4.2.6) lib/action_dispatch/routing/url_for.rb:156:in `url_for'    actionview (4.2.6) lib/action_view/routing_url_for.rb:83:in `url_for'    actionview (4.2.6) lib/action_view/helpers/form_tag_helper.rb:818:in `block in html_options_for_form'    actionview (4.2.6) lib/action_view/helpers/form_tag_helper.rb:814:in `tap'    actionview (4.2.6) lib/action_view/helpers/form_tag_helper.rb:814:in `html_options_for_form'    client_side_validations (4.2.5) lib/client_side_validations/action_view/form_tag_helper.rb:11:in `html_options_for_form'    actionview (4.2.6) lib/action_view/helpers/form_tag_helper.rb:68:in `form_tag'    app/views/map_fields/_map_fields.html.erb:1:in `_app_views_map_fields__map_fields_html_erb__4421720753810523207_114950960'    actionview (4.2.6) lib/action_view/template.rb:145:in `block in render'    activesupport (4.2.6) lib/active_support/notifications.rb:166:in `instrument'    actionview (4.2.6) lib/action_view/template.rb:333:in `instrument'    actionview (4.2.6) lib/action_view/template.rb:143:in `render'    actionview (4.2.6) lib/action_view/renderer/partial_renderer.rb:339:in `render_partial'    actionview (4.2.6) lib/action_view/renderer/partial_renderer.rb:310:in `block in render'    actionview (4.2.6) lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'    activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'    actionview (4.2.6) lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'    actionview (4.2.6) lib/action_view/renderer/partial_renderer.rb:309:in `render'    actionview (4.2.6) lib/action_view/renderer/renderer.rb:51:in `render_partial'    actionview (4.2.6) lib/action_view/renderer/renderer.rb:25:in `render'    actionview (4.2.6) lib/action_view/helpers/rendering_helper.rb:32:in `render'    app/views/contacts/mapper.html.erb:6:in `_app_views_contacts_mapper_html_erb__581327880311440466_115596220'    actionview (4.2.6) lib/action_view/template.rb:145:in `block in render'    activesupport (4.2.6) lib/active_support/notifications.rb:166:in `instrument'    actionview (4.2.6) lib/action_view/template.rb:333:in `instrument'    actionview (4.2.6) lib/action_view/template.rb:143:in `render'    actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'    actionview (4.2.6) lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'    activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'    actionview (4.2.6) lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'    actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'    actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'    actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:52:in `render_template'    actionview (4.2.6) lib/action_view/renderer/template_renderer.rb:14:in `render'    actionview (4.2.6) lib/action_view/renderer/renderer.rb:46:in `render_template'    actionview (4.2.6) lib/action_view/renderer/renderer.rb:27:in `render'    actionview (4.2.6) lib/action_view/rendering.rb:100:in `_render_template'    actionpack (4.2.6) lib/action_controller/metal/streaming.rb:217:in `_render_template'    actionview (4.2.6) lib/action_view/rendering.rb:83:in `render_to_body'    actionpack (4.2.6) lib/action_controller/metal/rendering.rb:32:in `render_to_body'    actionpack (4.2.6) lib/action_controller/metal/renderers.rb:37:in `render_to_body'    actionpack (4.2.6) lib/abstract_controller/rendering.rb:25:in `render'    actionpack (4.2.6) lib/action_controller/metal/rendering.rb:16:in `render'    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'    activesupport (4.2.6) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'    /home/myuser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'    activesupport (4.2.6) lib/active_support/core_ext/benchmark.rb:12:in `ms'    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:44:in `block in render'    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'    activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:43:in `render'    remotipart (1.2.1) lib/remotipart/render_overrides.rb:14:in `render_with_remotipart'    app/controllers/contacts_controller.rb:143:in `mapper'    actionpack (4.2.6) lib/action_controller/metal/implicit_render.rb:4:in `send_action'    actionpack (4.2.6) lib/abstract_controller/base.rb:198:in `process_action'    actionpack (4.2.6) lib/action_controller/metal/rendering.rb:10:in `process_action'    actionpack (4.2.6) lib/abstract_controller/callbacks.rb:20:in `block in process_action'    activesupport (4.2.6) lib/active_support/callbacks.rb:117:in `call'    activesupport (4.2.6) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'    activesupport (4.2.6) lib/active_support/callbacks.rb:505:in `call'    activesupport (4.2.6) lib/active_support/callbacks.rb:92:in `__run_callbacks__'    activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'    activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'    actionpack (4.2.6) lib/abstract_controller/callbacks.rb:19:in `process_action'    actionpack (4.2.6) lib/action_controller/metal/rescue.rb:29:in `process_action'    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'    activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'    activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'    actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action'    actionpack (4.2.6) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'    activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:18:in `process_action'    actionpack (4.2.6) lib/abstract_controller/base.rb:137:in `process'    actionview (4.2.6) lib/action_view/rendering.rb:30:in `process'    actionpack (4.2.6) lib/action_controller/metal.rb:196:in `dispatch'    actionpack (4.2.6) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'    actionpack (4.2.6) lib/action_controller/metal.rb:237:in `block in action'    actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'    actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:43:in `serve'    actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve'    actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `each'    actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve'    actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call'    meta_request (0.4.0) lib/meta_request/middlewares/app_request_handler.rb:13:in `call'    meta_request (0.4.0) lib/meta_request/middlewares/meta_request_handler.rb:13:in `call'    warden (1.2.6) lib/warden/manager.rb:35:in `block in call'    warden (1.2.6) lib/warden/manager.rb:34:in `catch'    warden (1.2.6) lib/warden/manager.rb:34:in `call'    client_side_validations (4.2.5) lib/client_side_validations/middleware.rb:15:in `call'    rack (1.6.4) lib/rack/etag.rb:24:in `call'    rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'    rack (1.6.4) lib/rack/head.rb:13:in `call'    remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call'    rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'    rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'    activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call'    activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'    activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__'    activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'    activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'    actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'    rails-dev-tweaks (1.2.0) lib/rails_dev_tweaks/granular_autoload/middleware.rb:36:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'    airbrake (4.3.8) lib/airbrake/rails/middleware.rb:13:in `call'    better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'    better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'    better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'    rack-contrib (1.4.0) lib/rack/contrib/response_headers.rb:17:in `call'    meta_request (0.4.0) lib/meta_request/middlewares/headers.rb:16:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'    railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'    railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'    activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'    activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'    activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'    railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'    rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'    rack (1.6.4) lib/rack/runtime.rb:18:in `call'    activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'    rack (1.6.4) lib/rack/lock.rb:17:in `call'    actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'    rack (1.6.4) lib/rack/sendfile.rb:113:in `call'    airbrake (4.3.8) lib/airbrake/user_informer.rb:16:in `_call'    airbrake (4.3.8) lib/airbrake/user_informer.rb:12:in `call'    railties (4.2.6) lib/rails/engine.rb:518:in `call'    railties (4.2.6) lib/rails/application.rb:165:in `call'    rack (1.6.4) lib/rack/content_length.rb:15:in `call'    thin (1.5.1) lib/thin/connection.rb:81:in `block in pre_process'    thin (1.5.1) lib/thin/connection.rb:79:in `catch'    thin (1.5.1) lib/thin/connection.rb:79:in `pre_process'    thin (1.5.1) lib/thin/connection.rb:54:in `process'    thin (1.5.1) lib/thin/connection.rb:39:in `receive_data'    eventmachine (1.0.9.1) lib/eventmachine.rb:193:in `run_machine'    eventmachine (1.0.9.1) lib/eventmachine.rb:193:in `run'    thin (1.5.1) lib/thin/backends/base.rb:63:in `start'    thin (1.5.1) lib/thin/server.rb:159:in `start'    rack (1.6.4) lib/rack/handler/thin.rb:19:in `run'    rack (1.6.4) lib/rack/server.rb:286:in `start'    railties (4.2.6) lib/rails/commands/server.rb:80:in `start'    railties (4.2.6) lib/rails/commands/commands_tasks.rb:80:in `block in server'    railties (4.2.6) lib/rails/commands/commands_tasks.rb:75:in `tap'    railties (4.2.6) lib/rails/commands/commands_tasks.rb:75:in `server'    railties (4.2.6) lib/rails/commands/commands_tasks.rb:39:in `run_command!'    railties (4.2.6) lib/rails/commands.rb:17:in `<top (required)>'    bin/rails:4:in `require'    bin/rails:4:in `<main>'  

It is showing in following files:

In views/map_fields/_map_fields.html.erb:

<%= form_tag nil, :id => 'map_fields_form', :method => :post do -%>  

In controller:

class ContactsController < ApplicationController    require_dependency 'map_fields'    map_fields :mapper, ['First Name','Last Name', 'Email', 'Notes'], :file_field => :file, :params => [:contact]      def create      @user = User.find(params[:user_id])      @contact = @user.contacts.create(contact_params)      respond_to do |format|        if @contact.save          format.json { render :json => { :notice => 'Contact was successfully created!',:redirect => user_contacts_url} }          format.html { redirect_to(user_contacts_url(@user), :notice => 'Contact was successfully created!', :type => 'success') }         else          format.json { render :json => {:redirect => false} }          format.html { render :action => "edit" }        end      end    end    def import      @contact = Contact.new     end      def mapper      @contact = Contact.new(params[:contact])      count = 0        if fields_mapped?        mapped_fields.each do |row|          params[:contact] = {"user_id" => @current_user.id, "firstname" => row[0], "lastname" => row[1], "notes" => row[3], "email" => row[2].try(:strip)}          contact = Contact.new(params[:contact])            if contact.save            count = count + 1          end        end          if count > 0          flash[:notice] = "#{count} Contact(s) created"          redirect_to :action => :index        else           flash[:notice] = "No contact was created..."           redirect_to :action => :index        end        else        @best_row = @rows[1]        render #here I am getting error.      end        rescue MapFields::InconsistentStateError        flash[:error] = 'Please try again'        redirect_to :action => :import      rescue MapFields::MissingFileContentsError        flash[:error] = 'Please upload a file'        redirect_to :action => :import    end   # followed by some methods and contact_params  end  

If I am correct nil values are passed here, so that it is showing the error. Please help me.

How to code a unit conversion

Posted: 09 Jul 2016 02:11 AM PDT

I have a scenario where a user can enter a quantity, a "from unit" and a "to unit" and I wish the app to display the quantity converted. I am using RoR and Postgres.

For example: if the user entered 1000 grams to kilograms the app would return 1 kg if the user entered 12 eggs to dozen the app would return 1 dozen if the user entered 250 millilitres to litres the app would return .25 litres

I had thought of using two simple tables being:

Units:  ======  Unit_id | Unit_name  1       | Grams  2       | Kilograms  3       | Eggs  4       | Dozen  5       | Millilitres  6       | Litres  7       | Millimetres  8       | Centimetres  9       | Meters    Conversions:  ============  Conversion_id | From_unit_id | To_unit_id | Multiplier  1             | 1            | 2          | 1000  2             | 3            | 4          | 12  3             | 5            | 6          | 1000  4             | 7            | 8          | 10  5             | 8            | 9          | 100      

Whilst this works it has a couple of flaws that I have been unable to resolve:

1) The conversion only works one way. Meaning that without repeating the logic I can convert from Grams to Kilograms but not Kilograms to Grams.

2) The conversion is single step only. Meaning I can convert from millimetres to centimetres and centimetres to metres but I cannot convert from millimetres to metres.

Point (1) above can be resolved by duplicating every conversion with the inverse logic and point (2) can be resolved by including every conversion combination however this doesn't feel right.

Is there a better way of approaching this problem?

"File to import not found or unreadable: materialize": Materialize CSS in Rails

Posted: 09 Jul 2016 02:02 AM PDT

I'm trying to use the Materialize CSS framework in my rails project, but I'm running into the following error:

File to import not found or unreadable: materialize. Load paths:   /home/ubuntu/workspace/photoid/app/assets/images   /home/ubuntu/workspace/photoid/app/assets/javascripts   /home/ubuntu/workspace/photoid/app/assets/stylesheets   /home/ubuntu/workspace/photoid/vendor/assets/javascripts   /home/ubuntu/workspace/photoid/vendor/assets/stylesheets   /usr/local/rvm/gems/ruby-2.3.0/gems/web-console-2.0.0.beta3/app/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/web-console-2.0.0.beta3/app/assets/stylesheets   /usr/local/rvm/gems/ruby-2.3.0/gems/web-console-2.0.0.beta3/lib/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/web-console-2.0.0.beta3/vendor/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/turbolinks-2.5.3/lib/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/jquery-rails-4.1.1/vendor/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/font-awesome-rails-4.6.3.1/app/assets/fonts   /usr/local/rvm/gems/ruby-2.3.0/gems/font-awesome-rails-4.6.3.1/app/assets/stylesheets   /usr/local/rvm/gems/ruby-2.3.0/gems/cloudinary-1.2.0/vendor/assets/html   /usr/local/rvm/gems/ruby-2.3.0/gems/cloudinary-1.2.0/vendor/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/coffee-rails-4.1.1/lib/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/bootstrap-sass-3.3.6/assets/stylesheets   /usr/local/rvm/gems/ruby-2.3.0/gems/bootstrap-sass-3.3.6/assets/javascripts   /usr/local/rvm/gems/ruby-2.3.0/gems/bootstrap-sass-3.3.6/assets/fonts   /usr/local/rvm/gems/ruby-2.3.0/gems/bootstrap-sass-3.3.6/assets/images   /usr/local/rvm/gems/ruby-2.3.0/gems/bootstrap-sass-3.3.6/assets/stylesheets  

application.scss

/*  *= require_tree .  *= require_self  *= require font-awesome  */    // "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"    @import "materialize";  @import "bootstrap-sprockets";  @import "bootstrap";  

application.js

//= require jquery  //= require jquery_ujs  //= require materialize-sprockets  //= require bootstrap-sprockets  //= require turbolinks  //= require_tree .  //= require jquery.infinitescroll  

I do have the Materialize gem installed. Am I getting the error because I already have bootstrap installed? Thanks in advance!

how can I pass the value between controller methods and then to the view

Posted: 09 Jul 2016 04:49 AM PDT

I know it may be a duplicate question, but it really drives me crazy, how someone can help me..

In bills_controller, I have a post action: apply_repay_list, in this action I generate a form : @jd_form which has the detailed info about the bill, and can be auto submitted,I want to post it to payment action

the logic is : user is in myBills.html.erb, he can see how much money he should pay, at the bottom of the page, there is a pay bill button, when he clicks the button,it takes him to payment.html.erb, he can then choose the payment methods like paypal or alipay to pay the bill. The problem is: I can generate the form, but I'm confused about how to post it to payment action, when I click the pay bill button , I got nill class for html.safe, which means @jd_form never pass to the view what I'm doing worng ? can someone help? ​

# bills_controller         def apply_repay_list #post action          ..........         ......          trading = Trading.new          trading.user_id=@user.id          trading.trading_type=5          trading.money= total_remain_amount          trading.relate_ids = bill_ids[1,bill_ids.length-1]          trading.trading_status=2          trading.cporderid="order#{@user.id}_#{@user.mobile_number}_#{Time.now.to_i}"          trading.save          byebug          trading = Trading.find(trading.id)          @jd_form = Jd.gen_form(trading)          respond_to do |format|              format.html { redirect_to :action => 'payment' , result: @jd_form}             format.json { render json: {status:0,status_text:'ok',data:trading.simple_hash}}          end      ​         end    ​  ​  def payment  #get action    end  ​  end  ​  #view  #myBills.html.erb  <%= link_to "pay bill", payment_bills_path, class:"pos_fixed btn-css text_center color_gold font-18"%>  ​  #payment.html.erb  #this is a hidden button, cause the form will be auto submit, and then redirect to   #payment provider like paypal's page  <div style="display:none;">  <%= @jd_form.html_safe %>      </div>  

routes.rb

resources :bills do      collection do        get 'list'        post 'apply_repay'        post 'apply_repay_ahead'        post 'apply_repay_list'        get 'detail'        get 'myBills'        get 'myBillsDetail'        get 'payment'      end    end  

is gem respond_to_parent support in rails4.2.6

Posted: 09 Jul 2016 12:32 AM PDT

how gem respond_to_parent is support in rails 4.2.6 if not then what will be equivalent of this ?

 gem 'responds_to_parent', git: 'https://github.com/markcatley/responds_to_parent.git'     Error => undler/gems/responds_to_parent-e9e1250e3a48/lib/responds_to_parent.rb:7:in `<top (required)>': uninitialized constant ActionDispatch::Assertions::SelectorAssertions (NameError)  

And please let me know what will be the equivalent of below routes in rails 4 beacuse it's through error when rails server.

get ':controller/service.wsdl' => '#wsdl'  

/gems/actionpack-4.2.6/lib/action_dispatch/routing/mapper.rb:260:in `block (2 levels) in check_controller_and_action': '' is not a supported controller name. This can lead to potential routing problems. See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use (ArgumentError)

DEPRECATION WARNING: [paperclip] [deprecation] AWS SDK v1 has been deprecated in paperclip 5

Posted: 09 Jul 2016 12:26 AM PDT

Recently I migrated my Rails version from 3.2 to 4.2.6 and along with that I modify some gems like paperclip 2.3 to 4.3.6. When I run rails server, I am getting following deprecations:

DEPRECATION WARNING: [paperclip] [deprecation] AWS SDK v1 has been deprecated in paperclip 5. Please consider upgrading to AWS 2 before upgrading paperclip. (called from at /home/myuser/Desktop/project/app/models/user.rb:58) DEPRECATION WARNING: [paperclip] [deprecation] AWS SDK v1 has been deprecated in paperclip 5. Please consider upgrading to AWS 2 before upgrading paperclip. (called from at /home/myuser/Desktop/project/app/models/user.rb:72)

This is user.rb, line 58:

  has_attached_file :photo,      :styles => { :small => "125x125>" } ,      :storage => :s3,      :s3_credentials => "#{Rails.root.to_s}/config/s3.yml",      :path => "/:style/:id/:filename"  

This is user.rb, line 72:

  has_attached_file :logo,      :styles => { :small => "200x100>" } ,      :storage => :s3,      :s3_credentials => "#{Rails.root.to_s}/config/s3.yml",      :path => "/:style/:id/:filename"  

How to over come this deprecation? Please help

Updating field with Active Admin Batch Action (Rails)

Posted: 08 Jul 2016 11:04 PM PDT

I'm trying to update the field "validated" with the value true (if the "Ad" - the model - is selected).

I've tried to find an answer in the documentation, however its difficult to see how to update a field (the documentation talks about removal and flagging). Any help would be appreciated.

Current code (not working):

    batch_action :validated do |selection|      Ad.find(selection).each do |ad|        ad.validated => true      end    end  

Thanks!

Issue regarding ajax search rails

Posted: 08 Jul 2016 10:58 PM PDT

I tried to built my search with Ajax and I have added remote: true , and respond_ to block in the controller and I created the partial _xvaziri.html.erb and finally index.js.erb.

But I am not getting the desired results for the Ajax search.

Please refer the images as shown below;

screenshot.png

In the above image when I searched for "cash" then I get rendering multiple times in the terminal.

screenshot2.png

index.html.erb

<% @balance = 0 %>           <div class="row">        <div class="col-md-10 col-md-offset-1">            <div class="table-responsive myTable">                <table class="table listing text-center">                  <tr class="tr-head">                      <td>Date</td>                      <td>Description</td>                      <td>Amount</td>                      <td>Discount</td>                      <td>Paid</td>                      <td>Balance</td>                  </tr>                    <tr>                      <td></td>                  </tr>                      <a href="#" class="toggle-form" style="float: right;" >Search</a>                    <div id="sample">                    <%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>                  <p>                      <center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>                          <%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>                      </p>                      <% end %><br>    </div>                          <% if @xvaziris.empty? %>                            <center><p><em>No results found.</em></p></center>                                          <% end %>                            <%= render @xvaziris %>                        </table>                  </div>              </div>          </div>  

_xvaziri.html.erb

<tr  id = "kola" class="tr-<%= cycle('odd', 'even') %>">        <td class="col-1"><%= xvaziri.date.strftime('%d/%m/%Y') %></td>      <td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>          <td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>          <% @balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>        <% color = @balance >= 0 ? "pos" : "neg" %>        <td class="col-1 <%= color %>"><%= number_with_precision(@balance.abs, :delimiter => ",", :precision => 2) %></td>    </tr>  

xvaziris_controller.rb

class XvazirisController < ApplicationController        before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]          def index          @xvaziris = Xvaziri.where (["description LIKE ? OR amount LIKE ? OR paid LIKE ?", "%#{params[:search]}%","%#{params[:search]}%","%#{params[:search]}%"])           respond_to do |format|              format.js              format.html          end       end        def import          Xvaziri.import(params[:file])          redirect_to xvaziris_url, notice: "Xvaziris imported."      end        def show      end        def new          @xvaziri = Xvaziri.new      end        def create          @xvaziri = Xvaziri.new(xvaziri)          if              @xvaziri.save              flash[:notice] = 'Xvaziri Created'              redirect_to @xvaziri          else              render 'new'          end      end        def edit      end        def update          if @xvaziri.update(xvaziri)              flash[:notice] = 'Xvaziri Updated'              redirect_to @xvaziri          else              render 'edit'          end        end        def destroy          @xvaziri.destroy          flash[:notice] = 'Xvaziri was successfully destroyed.'          redirect_to xvaziris_url          end        private      # Use callbacks to share common setup or constraints between actions.      def set_xvaziri          @xvaziri = Xvaziri.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def xvaziri          params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)      end    end  

index.js.erb

<% @balance = 0 %>      <% @xvaziris.each do |xvaziri| %>        $('#kola').append("<%= j render xvaziri %>");      <% end %>  

How should I write the above code in order to find searches in xvaziris#index ?

Secondly, I want to display the no results found when search is nil,blank or empty.I wrote the below code but it is not working.

<% if @xvaziris.empty? %>          <center><p><em>No results found.</em></p></center>                   <% end %>  

Any suggestions are most welcome.

Thank you in advance.

undefined method `write_inheritable_attribute' for ContactsController:Class

Posted: 09 Jul 2016 12:28 AM PDT

I upgraded my Rails version from 3.2.13 to Rails 4.2.6. In the older version, they used map_fields plugin where in my contacts controller:

class ContactsController < ApplicationController    require 'map_fields'    map_fields :mapper, ['First Name','Last Name', 'Email', 'Notes'], :file_field => :file, :params => [:contact]      def create      @user = User.find(params[:user_id])      @contact = @user.contacts.create(contact_params)      respond_to do |format|        if @contact.save          format.json { render :json => { :notice => 'Contact was successfully created!',:redirect => user_contacts_url} }          format.html { redirect_to(user_contacts_url(@user), :notice => 'Contact was successfully created!', :type => 'success') }         else          format.json { render :json => {:redirect => false} }          format.html { render :action => "edit" }        end      end    end    def import      @contact = Contact.new     end      def mapper      @contact = Contact.new(params[:contact])      count = 0        if fields_mapped?        mapped_fields.each do |row|          params[:contact] = {"user_id" => @current_user.id, "firstname" => row[0], "lastname" => row[1], "notes" => row[3], "email" => row[2].try(:strip)}          contact = Contact.new(params[:contact])            if contact.save            count = count + 1          end        end          if count > 0          flash[:notice] = "#{count} Contact(s) created"          redirect_to :action => :index        else           flash[:notice] = "No contact was created..."           redirect_to :action => :index        end        else        @best_row = @rows[1]        render      end        rescue MapFields::InconsistentStateError        flash[:error] = 'Please try again'        redirect_to :action => :import      rescue MapFields::MissingFileContentsError        flash[:error] = 'Please upload a file'        redirect_to :action => :import    end    end  

when I run the code I am getting the error

ActionController::RoutingError - undefined method `write_inheritable_attribute' for ContactsController:Class:  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:63:in `rescue in controller'  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:58:in `controller'  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:39:in `serve'  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve'  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve'  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call'  meta_request (0.4.0) lib/meta_request/middlewares/app_request_handler.rb:13:in `call'  meta_request (0.4.0) lib/meta_request/middlewares/meta_request_handler.rb:13:in `call'  warden (1.2.6) lib/warden/manager.rb:35:in `block in call'  warden (1.2.6) lib/warden/manager.rb:34:in `call'  client_side_validations (4.2.5) lib/client_side_validations/middleware.rb:15:in `call'  rack (1.6.4) lib/rack/etag.rb:24:in `call'  rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'  rack (1.6.4) lib/rack/head.rb:13:in `call'  remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call'  rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'  rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'  activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call'  activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'  activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__'  activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'  activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'  actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'  rails-dev-tweaks (1.2.0) lib/rails_dev_tweaks/granular_autoload/middleware.rb:36:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'  airbrake (4.3.8) lib/airbrake/rails/middleware.rb:13:in `call'  better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'  better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'  rack-contrib (1.4.0) lib/rack/contrib/response_headers.rb:17:in `call'  meta_request (0.4.0) lib/meta_request/middlewares/headers.rb:16:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'  railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'  railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'  railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'  rack (1.6.4) lib/rack/runtime.rb:18:in `call'  activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  rack (1.6.4) lib/rack/lock.rb:17:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'  airbrake (4.3.8) lib/airbrake/user_informer.rb:16:in `_call'  airbrake (4.3.8) lib/airbrake/user_informer.rb:12:in `call'  railties (4.2.6) lib/rails/engine.rb:518:in `call'  railties (4.2.6) lib/rails/application.rb:165:in `call'  rack (1.6.4) lib/rack/content_length.rb:15:in `call'  thin (1.5.1) lib/thin/connection.rb:81:in `block in pre_process'  thin (1.5.1) lib/thin/connection.rb:79:in `pre_process'  thin (1.5.1) lib/thin/connection.rb:54:in `process'  thin (1.5.1) lib/thin/connection.rb:39:in `receive_data'  eventmachine (1.0.9.1) lib/eventmachine.rb:193:in `run'  thin (1.5.1) lib/thin/backends/base.rb:63:in `start'  thin (1.5.1) lib/thin/server.rb:159:in `start'  rack (1.6.4) lib/rack/handler/thin.rb:19:in `run'  rack (1.6.4) lib/rack/server.rb:286:in `start'  railties (4.2.6) lib/rails/commands/server.rb:80:in `start'  railties (4.2.6) lib/rails/commands/commands_tasks.rb:80:in `block in server'  railties (4.2.6) lib/rails/commands/commands_tasks.rb:75:in `server'  railties (4.2.6) lib/rails/commands/commands_tasks.rb:39:in `run_command!'  railties (4.2.6) lib/rails/commands.rb:17:in `<top (required)>'  bin/rails:4:in `<main>'  

This is my routes.rb file:

Htm::Application.routes.draw do    .......................other routes......    resources :contacts do        post :import_remote,  :on => :collection        get :import_remote,   :on => :collection        collection  do          post    :mapper          get     :import          post    :destroy_multiple          delete  :destroy_all        end      end  end  

I followed the same steps you given in issue 1, but I am getting this error. Please help.

rails assets precompile error with a js with variable definitions with a -. works on one computer and in other not

Posted: 09 Jul 2016 04:17 AM PDT

I'm running RAILS_ENV=production bundle exec rake assets:precompile and getting this error

...somefile.js  ExecJS::ProgramError: Unexpected token: operator (-) (line: 3, col: 9, pos: 11)  

This is the content of that line:

var color-green="#27cebc";  

I guess the problem is because the variable name includes a -. However using the same ruby version on local computer with same command, it's able to process correctly without the error:

On my local computer:

RAILS_ENV=production bundle exec rake assets:precompile`  

And it was able to process the offending file without problems, and generated this file:

public/assets/js/some=file-68c9a5f2e1f2216c5d3d2b9fcd7741155113425f7f46f18187ad5b98e1a11092.js    $ ruby -v  ruby 2.2.1p85  $ gem list | grep js  execjs (2.5.2)  

I tried commenting the line out and it process all the files succesfully, but I dont understand why on local it works with that line, and in the server doesnt.

JSON.parse on an API Response more than once?

Posted: 08 Jul 2016 10:05 PM PDT

I'm making my first rails app which is a connector to a legacy ecommerce framework to the ship hero warehouse management system.

I'm hitting a wall on a certain issue. I have created a webhook and registered it in the ship hero api. When a shipment goes out it sends data to an endpoint I've created. I received the parameters as so:

Started POST "/ship" for 54.243.50.75 at 2016-07-08 15:22:02 -0400

Processing by WebhooksController#shipment as */*    Parameters: {"{\"test\": \"0\", \"fulfillment\": {\"line_items\": "=>{"{\"id\": \"200CB01-606R\", \"quantity\": 1}"=>{", \"shipping_method\": \"UPS Ground\", \"shipping_carrier\": \"UPS\", \"tracking_number\": \"1Z89ER740392038191\", \"custom_tracking_url\": \"http://wwwapps.ups.com/WebTracking/track?track"=>"yes"}}, "trackNums"=>"1Z89ER740392038191\", \"shipping_address\": {\"address_city\": \"Brooklyn\", \"name\": \"XXX\", \"address1\": \"XXX\", \"address2\": \"APT 2A\", \"address_state\": \"NY\", \"address_country\": \"US\", \"address_zip\": \"11222\"}, \"order_number\": \"WS987182\"}}"}

the controller action I have set up is:

def shipment      if request.headers['Content-Type'] == 'application/json'        data = JSON.parse(request.body.read)             x = JSON.parse(request.body.read)["fulfillment"]["order_number"]         y = JSON.parse(request.body.read)["fulfillment"]["tracking_number"]         puts x         puts y        render nothing: true      else        # application/x-www-form-urlencodedw        data = params.as_json            x = JSON.parse(request.body.read)["fulfillment"]["order_number"]        y = JSON.parse(request.body.read)["fulfillment"]["tracking_number"]        puts x        puts y        render nothing: true      end    end  

this throws an error: JSON::ParserError: A JSON text must at least contain two octets! But if I remove one of the x or y variables from each conditional it parses the correct value i am looking for ( the tracking number or order number). So as long as I only parse 1 value it works. I don't understand why. Here is the link to the ship hero apiary for the Webhook Shipment URL documentation. Any help would be greatly appreciated.

Gemfile is not using the specified ruby version

Posted: 08 Jul 2016 09:41 PM PDT

I'm making a project and when I run a generate command I get the following error:

fullpath: /Users/adamgoldberg/shopify-sinatra-app/theappearsystemcontrol6  Your Ruby version is 2.3.1, but your Gemfile specified 2.2.2  Bundler::RubyVersionMismatch: Your Ruby version is 2.3.1, but your Gemfile specified 2.2.2    /Users/adamgoldberg/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:417:in `validate_ruby!'    /Users/adamgoldberg/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler.rb:91:in `setup'    /Users/adamgoldberg/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/setup.rb:19:in `<top (required)>'    /Users/adamgoldberg/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'    /Users/adamgoldberg/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'bundler: failed to load command: rake (/Users/adamgoldberg/.rbenv/versions/2.3.1/bin/rake)  

I have to use ruby version 2.3.1 for my project so I have attempted changing my Gemfile version. my gemfile now contains this:

ruby "~> 2.3"  

I have tried all sorts of commands so that the Gemfile recognises that I want to use a different ruby version. I have tried:

bundle update  bundle install  gem bundle install  rbenv rehash  

even my Gemfile.lock says it is using 2.3.1:

RUBY VERSION      ruby 2.3.1p112  

I have even deleted the project and started again.

Please help


An update: I deleted the project and restarted. here are the exact steps I took from my home directory

ruby -v: #2.3.1  git clone https://github.com/kevinhughes27/shopify-sinatra-app.git  gem install shopify-sinatra-app  shopify-sinatra-app-generator new myshop  

and the same error as above appeared:

Your Ruby version is 2.3.1, but your Gemfile specified 2.2.2  

My Gemfile looks like this:

source 'https://rubygems.org'  gemspec  

it's practically empty... I haven't even specified the ruby version I then ran

bundle install   bundle update  

still the same error appears. I then specified in my Gemspect the ruby version and it now looks like this:

source 'https://rubygems.org'  ruby "2.3.1"  gemspec  

but still the same error appears

Axlsx automatic chart size

Posted: 09 Jul 2016 12:51 AM PDT

I am using the axlsx and axlsx_rails gem, I want to know if there is a way to set the chart (ex: Bar3DChart) size automatically.

Now I am using the "fixed" way using start_at and end_at

sheet.add_chart(Axlsx::Bar3DChart, :start_at => "A1", :end_at => "M40")  

Thanks

Psych::SyntaxError: (<unknown>): mapping values are not allowed

Posted: 08 Jul 2016 07:44 PM PDT

I'm trying to rest my rails db or drop the db and aways show this message, please someone have any idea what this" Psych::SyntaxError: (): mapping values have to do with the db?

thank's

 ** Invoke db:drop:all (first_time)  ** Invoke db:load_config (first_time)  ** Execute db:load_config  rake aborted!  Psych::SyntaxError: (<unknown>): mapping values are not allowed in this context at line 28 column 9  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/2.2.0/psych.rb:370:in `parse'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/2.2.0/psych.rb:370:in `parse_stream'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/2.2.0/psych.rb:318:in `parse'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/2.2.0/psych.rb:245:in `load'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/railties-3.2.22/lib/rails/application/configuration.rb:115:in `database_configuration'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/activerecord-3.2.22/lib/active_record/railties/databases.rake:25:in `block (2 levels) in <top (required)>'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `call'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:209:in `block in invoke_prerequisites'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:207:in `each'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:207:in `invoke_prerequisites'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:186:in `block in invoke_with_call_chain'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:152:in `invoke_task'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block (2 levels) in top_level'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `each'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block in top_level'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:117:in `run_with_threads'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:102:in `top_level'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:80:in `block in run'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/lib/rake/application.rb:77:in `run'  /Users/danielcalixto/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'  /Users/danielcalixto/.rbenv/versions/2.2.2/bin/rake:23:in `load'  /Users/danielcalixto/.rbenv/versions/2.2.2/bin/rake:23:in `<main>'  Tasks: TOP => db:drop:all => db:load_config  

Rails User has_many completions through lessons: Boolean Controller and Routes

Posted: 08 Jul 2016 06:28 PM PDT

Ok, I'm a novice rails developer and I've been thinking about this project all day and I'm not exactly sure how to do it and was looking for some clarification on the Controller, Routes and button logic portion of this project. I understand the model layout. I think.

The basic functional description goes as follows:
User views a video lesson and then clicks a button to mark the lesson as completed after viewing the video and then is redirected to the next video lesson (assuming they're in order by lesson_id). Button colors changes to indicate the lesson has been viewed and the Completions table gets updated to indicated that the lesson has been completed (boolean).

Here's the overview of my models:

User     has_many :completions     has_many :completed_steps, through: :completions, source: :lesson    Lesson     has_many :completions     has_many :completed_by, through: :completions, source: :user    Completions     belongs_to :user     belongs_to :lesson  

My Completions Table looks like this:

    t.integer  "user_id"      t.integer  "lesson_id"      t.boolean  "completed_step"      t.string   "completed_by"  

So I'm guessing I need to add a Completions Controller and implement a method whereby the completed_step boolean gets updated as well as the appropriate user_id, lesson_id and maybe the completed_by as well (although I view that one as optional) get updated??

Here's what I don't know and it doesn't seem terribly straightforward.

The controller logic...

CompletionsController or LessonsController??  def complete_lesson     what goes in here?        end  

And then the routes.rb logic??

match '/completions/complete_lesson' => 'completions#complete_lesson', as: 'lesson_complete'  

Then the button will look something like this then I guess??

<% if current_user.completed_steps.include? @lesson %>      <% if @lesson.next %>          <%= button_to "Completed", lesson_path(@lesson.next), class: "btn btn-success btn-lg" %>      <% end %>      <% else %>           <%= button_to "Mark this Lesson as Complete", lesson_complete_path(@lesson), method: :put, class: "btn btn-warning btn-lg" %>  <% end %>  

how to get key in ruby on rails .each loop

Posted: 08 Jul 2016 06:38 PM PDT

In laravel I am use to being able to access the key in a loop. In rails I cannot find answer to how to get that from the loop.

Standard loop like so

<% @subjects.each do |subject| %>       <div class="col-md-6 subjectColumn">         <div class="subjectBox subjectBox-<%= key %>">             <h2><%= subject.title.capitalize %><h2>              <p><%= subject.description %></p>                 <a href="/subjects/<%= subject.id %>">View courses<i class="fa fa-angle-right"></i></a></h2>         </div>       </div>    <% end %>  

I want to add the integer for the key in the code above. I have tried...

<% @subjects.keys.each do |key, subject|  

...and other various things I found here and elsewhere but nothing worked. The above code created an error. Most of the things I found just did not give any number. Any help with this would be greatly appreciated. I feel I probably just have not got the syntax quite correct or something.

Call controller action when user clicks on a table cell

Posted: 08 Jul 2016 05:01 PM PDT

I have a table in my view. How do I call a controller action ("update") when the listener clicks on table cell. I also need to send arguments to the controller.

Does this need AJAX?

wrong username/ password error-handling using httparty

Posted: 08 Jul 2016 08:32 PM PDT

I am creating a local gem utilizing httparty to connect to specific website to get auth token. I was able to get the program to fetch auth_token when I entered the correct email and password. However, if I put the wrong email/password, it returns: NameError: uninitialized constant Gemname::InvalidStudentCodeError

require 'httparty'  class Gemname    include HTTParty      def initialize(email, password)      response = self.class.post("https://www.website.io/api/v1/sessions", body: {"email": email, "password": password})  #####error-handler#####      if StandardError        puts "invalid email/pass"      end  #######################      @auth_token = response["auth_token"]    end  end  

It seems like most errors are categorized under standard error.

The idea is to run from irb Gemname.new('email', 'wrong-password'), it would return "Wrong email/password". How should I handle the error to display the proper message?

Edit: I tried these codes on initialize:

if StandardError    "error"  end  

I also tried

created on lib folder, a folder named gemname -> error.rb error.rb:

class InvalidStudentCodeError < StandardError    def initialize(msg="invalid email or password")      super(msg)    end  end  

and on initialize:

raise InvalidStudentCodeError.new() if response.code == 401  

Why does my login page work on one branch and not the other?

Posted: 08 Jul 2016 05:02 PM PDT

I am working on my blogapp while following guidance from Michael Hartl's Rails tutorial.

When I am on one branch (non-master), the login page populates fine when I request the page. However, when I am on another branch (also non-master), I get the following error:

Have I merged branches incorrectly?

users_controller.rb

    class UsersController < ApplicationController     before_action :logged_in_user, only: [:index, :edit, :update]    before_action :correct_user,   only: [:edit, :update]      def show      @user = User.find(params[:id])    end      def new      @user = User.new    end      def create      @user = User.new(user_params)      if @user.save        log_in @user        flash[:success] = "Welcome to the Sample App!"        redirect_to @user      else        render 'new'      end    end      def edit      @user = User.find(params[:id])    end    def index      @users = User.all    end    def update      @user = User.find(params[:id])      if @user.update_attributes(user_params)        # Handle a successful update.      else        render 'edit'      end    end      private        def user_params        params.require(:user).permit(:name, :email, :password,                                     :password_confirmation)      end      # Before filters        # Confirms a logged-in user.      def logged_in_user        unless logged_in?          store_location          flash[:danger] = "Please log in."          redirect_to login_url        end      end        # Confirms the correct user.      def correct_user        @user = User.find(params[:id])        redirect_to(root_url) unless current_user?(@user)      end  end    routes.rb       Rails.application.routes.draw do    get 'users/new'      get 'blog_pages/home'      get 'about' => 'blog_pages#about'      get 'goodstuff' => 'blog_pages#goodstuff'      get 'serenity' => 'blog_pages#serenity'      get 'contact' => 'blog_pages#contact'      get 'signup' => 'users#new'    resources :users      # The priority is based upon order of creation: first created -> highest priority.    # See how all your routes lay out with "rake routes".      # You can have the root of your site routed with "root"  root 'application#Blog'      # Example of regular route:    #   get 'products/:id' => 'catalog#view'      # Example of named route that can be invoked with purchase_url(id: product.id)    #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase      # Example resource route (maps HTTP verbs to controller actions automatically):    #   resources :products      # Example resource route with options:    #   resources :products do    #     member do    #       get 'short'    #       post 'toggle'    #     end    #    #     collection do    #       get 'sold'    #     end    #   end      # Example resource route with sub-resources:    #   resources :products do    #     resources :comments, :sales    #     resource :seller    #   end      # Example resource route with more complex sub-resources:    #   resources :products do    #     resources :comments    #     resources :sales do    #       get 'recent', on: :collection    #     end    #   end      # Example resource route with concerns:    #   concern :toggleable do    #     post 'toggle'    #   end    #   resources :posts, concerns: :toggleable    #   resources :photos, concerns: :toggleable      # Example resource route within a namespace:    #   namespace :admin do    #     # Directs /admin/products/* to Admin::ProductsController    #     # (app/controllers/admin/products_controller.rb)    #     resources :products    #   end  end  

fields_for doesn't save object sin rails

Posted: 09 Jul 2016 04:16 AM PDT

Im interested why does my nested form in RoR doesnt save child objects :(

For now, it just save the Parent (Printer) value and makes the child(Color) disappear on second render (error)! What Am I doing wrong?

Parent model

class Printer < ActiveRecord::Base  belongs_to :user  validates :user_id, presence: true  validates :model, presence: true    has_many :colors, dependent: :destroy  accepts_nested_attributes_for :colors  end  

Child model

class Color < ActiveRecord::Base      belongs_to :printer      validates :color, presence: true    end  

View (new.html.erb)

      <%= form_for @printer do |p|%>          <%= p.text_field :model %>        <%= p.fields_for :colors do |color|%>            <%= color.text_field :color%>        <% end %>          <%= p.submit "Add"%>    <% end %>  

And controller

def create  @printer = current_user.printers.build(printer_params)  if @printer.save    redirect_to @current_user  else    render 'new'  end  end    def new   @printer = Printer.new   @printer.colors.build  end    private  def printer_params    params.require(:printer).permit(:model)  end  

Edit: This one helps

private  def printer_params    params.require(:printer).permit(:model, colors_attributes: [:color])  end  

1 comment:

  1. No Implicit Conversion Of Symbol Into Integer - Working With Param From Url >>>>> Download Now

    >>>>> Download Full

    No Implicit Conversion Of Symbol Into Integer - Working With Param From Url >>>>> Download LINK

    >>>>> Download Now

    No Implicit Conversion Of Symbol Into Integer - Working With Param From Url >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete