dimanche 28 juin 2015

Failure/Error: visit movie_url(movie) ActionView::Template::Error: wrong number of arguments (3 for 0..1)

This question sounds very similar to those that have already been asked and answered thought I can't seem to figure it out.

I have the following error message that makes my spec test fail.

Failures:

  1) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # ./app/views/movies/show.html.erb:24:in `_app_views_movies_show_html_erb__1138068182152565203_70152862507580'
     # ./spec/navigate_movies_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 0.20747 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

Randomized with seed 14064

My actual spec test looks like this:

require 'spec_helper'
include Rails.application.routes.url_helpers

  describe "Navigating movies" do
    it "allows navigation from the detail page to the listing page" do
    ...
    visit movie_url(movie)

    click_link "All Movies"

    expect(current_path).to eq(movies_path)
  end
end

My show page: <%= link_to "All Movies", movies_path %> Edited:

rake routes
Prefix Verb URI Pattern           Controller#Action
movies GET  /movies(.:format)     movies#index
 movie GET  /movies/:id(.:format) movies#show

Edit #3

bundle exec rspec -b
FF.

Failures:

  1) Viewing an individual movie shows the movie's details
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/url_for.rb:150:in `url_for'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:280:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:223:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:345:in `block (2 levels) in define_url_helper'
     # ./app/views/movies/show.html.erb:23:in `_app_views_movies_show_html_erb__342552887677354596_70168586387480'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:145:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:166:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:333:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:143:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:52:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:14:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:42:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:23:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:100:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/streaming.rb:217:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:83:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:32:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/renderers.rb:37:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/rendering.rb:25:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:16:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
     # /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `ms'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:43:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:10:in `default_render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:5:in `send_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:198:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:10:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:20:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:92:in `_run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:776:in `_run_process_action_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:81:in `run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:19:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rescue.rb:29:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:137:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:30:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal.rb:196:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal.rb:237:in `block in action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:74:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:43:in `serve'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/journey/router.rb:43:in `block in serve'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/journey/router.rb:30:in `each'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/journey/router.rb:30:in `serve'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:819:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/etag.rb:24:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/conditionalget.rb:25:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/head.rb:13:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/params_parser.rb:27:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/flash.rb:260:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/session/abstract/id.rb:225:in `context'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/session/abstract/id.rb:220:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/cookies.rb:560:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/query_cache.rb:36:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:649:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:88:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:88:in `_run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:776:in `_run_call_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:81:in `run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.3/lib/web_console/middleware.rb:37:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/rack/logger.rb:38:in `call_app'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/rack/logger.rb:20:in `block in call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/tagged_logging.rb:68:in `block in tagged'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/tagged_logging.rb:26:in `tagged'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/tagged_logging.rb:68:in `tagged'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/rack/logger.rb:20:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/request_id.rb:21:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/methodoverride.rb:22:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/runtime.rb:18:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/lock.rb:17:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/static.rb:113:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/sendfile.rb:113:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/engine.rb:518:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/application.rb:164:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/urlmap.rb:66:in `block in call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/urlmap.rb:50:in `each'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/urlmap.rb:50:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-test-0.6.3/lib/rack/mock_session.rb:30:in `request'
     # /Library/Ruby/Gems/2.0.0/gems/rack-test-0.6.3/lib/rack/test.rb:244:in `process_request'
     # /Library/Ruby/Gems/2.0.0/gems/rack-test-0.6.3/lib/rack/test.rb:58:in `get'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/browser.rb:59:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/browser.rb:35:in `process_and_follow_redirects'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/browser.rb:21:in `visit'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/driver.rb:42:in `visit'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/session.rb:193:in `visit'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/dsl.rb:51:in `block (2 levels) in <module:DSL>'
     # ./spec/show_movie_spec.rb:9:in `block (2 levels) in <top (required)>'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:114:in `instance_eval'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:114:in `block in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:179:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:179:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/extensions/instance_eval_with_args.rb:16:in `instance_exec'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/extensions/instance_eval_with_args.rb:16:in `instance_eval_with_args'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:247:in `instance_eval_with_args'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:87:in `block (2 levels) in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:89:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:89:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:418:in `run_hook'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:329:in `run_around_each_hooks'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:256:in `with_around_each_hooks'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:111:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:390:in `block in run_examples'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:386:in `map'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:386:in `run_examples'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:371:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `block (2 levels) in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `map'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `block in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/reporter.rb:34:in `report'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:25:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'

  2) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie.to_param)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/url_for.rb:150:in `url_for'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:280:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:223:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:345:in `block (2 levels) in define_url_helper'
     # ./app/views/movies/show.html.erb:23:in `_app_views_movies_show_html_erb__342552887677354596_70168586387480'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:145:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:166:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:333:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:143:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:52:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:14:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:42:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:23:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:100:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/streaming.rb:217:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:83:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:32:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/renderers.rb:37:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/rendering.rb:25:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:16:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
     # /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `ms'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:43:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:10:in `default_render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:5:in `send_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:198:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:10:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:20:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:92:in `_run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:776:in `_run_process_action_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:81:in `run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:19:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rescue.rb:29:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:137:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:30:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal.rb:196:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'

Finished in 0.84651 seconds
3 examples, 2 failures

Failed examples:

rspec ./spec/show_movie_spec.rb:6 # Viewing an individual movie shows the movie's details
rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

rake db:seed -> Mongoid::Errors::NoSessionConfig:

I am building an application in ROR using SQLite.

In the project I include a gem which has run time dependency in Mongoid.

However for my case, I do not use mongoid or any mongodb.

When I am running rake db:seed which I use to fill the fields in my sql database I receive the specific error:

rake aborted!

Mongoid::Errors::NoSessionConfig: Problem: No configuration could be found for a session named 'default'. Summary: When attempting to create the new session, Mongoid could not find a session configuration for the name: 'default'. This is necessary in order to know the host, port, and options needed to connect. Resolution: Double check your mongoid.yml to make sure under the sessions key that a configuration exists for 'default'. If you have set the configuration programatically, ensure that 'default' exists in the configuration hash.

Passing variable to partial inside partial

In the view.html.erb:

<%= render @posts %>

In each _post.html.erb:

<%= render 'shared/block', blockedcallsign: post.callsign %>

In each _block.html.erb:

<%= button_to blockrelationships_path, class: 'btn btn-default btn-xs',
                        params: { 
                            blocker_callsign: @callsign, 
                            blocked_callsign: @blockedcallsign
                        },
                        remote: true do %>
<% end %>

Looking at the server logs, the blocked_callsign parameter is blank. I'm not passing the variable to the partial correctly. What's wrong with the code?

EDIT

With blockedcallsign instead of @blockedcallsign in _block.html.erb:

<%= button_to blockrelationships_path, class: 'btn btn-default btn-xs',
                        params: { 
                            blocker_callsign: @callsign, 
                            blocked_callsign: blockedcallsign
                        },
                        remote: true do %>
<% end %>

and the following in _post.html.erb:

<%= render 'shared/block', locals: { blockedcallsign: post.callsign } %>

I get the error: undefined local variable or method 'blockedcallsign'.

Why this won't fetch particular page of the result set?

Following youtube's official API document, I made this code below.
It shows fine if I take off

:pageToken => 5

How can I fetch particular page of the result sets?(I mean pagination here)

Original Code

@search_response = client.execute!(
  :api_method => youtube.search.list,
  :parameters => {
    :part => 'snippet',
    :q => 'cat',
    :maxResults => 10,
    :order => 'date',
    :pageToken => 5
  }
)

Rails Bootstrap_form - Radio buttons not rendering label name in the show page

I have a form built with the bootstrap_form gem for ruby. within the form I have some radio buttons. the form renders perfectly with the correct labeling in the edit page of the form, however once I save the form and go to the "show" page to see the results, the inputs for the radio buttons are only showing the value of the radio button (which are numbers) and not the custom label name I have assigned. How can I make the custom label appear instead of the value in the show page?

Here is my code:

_form.html.erb:

  <%= f.form_group :gender, label: { text: "Gender" } do %>
    <%= f.radio_button :gender, 0, label: "Female", checked: true, inline: true  %>
    <%= f.radio_button :gender, 1, label: "Male", inline: true  %>
  <% end %>

  <%= f.form_group :nationality, label: { text: "Nationality" } do %>
    <%= f.radio_button :nationality, 0, label: "Kuwaiti", checked: true, inline: true  %>
    <%= f.radio_button :nationality, 1, label: "Non-Kuwaiti", inline: true  %>
  <% end %>

show.html.erb

    <p><strong>Full Name:</strong>&nbsp;&nbsp;<%= @profile.name %></p>
    <p><strong>Civil ID no:</strong>&nbsp;&nbsp;<%= @profile.civil %></p>
    <p><strong>Gender:</strong>&nbsp;&nbsp;<%= @profile.gender %></p>
    <p><strong>Nationality:</strong>&nbsp;&nbsp;<%= @profile.nationality %></p>
    <p><strong>Mobile no:</strong>&nbsp;&nbsp;<%= @profile.mobile %></p>
    <p><strong>Personal Email:</strong>&nbsp;&nbsp;<%= @profile.personal_email %></p>

Thanks for the help in advance!

Update:-

New form code:-

<%= f.form_group :gender, label: { text: "Gender" } do %>
    <%= f.radio_button :gender, 1  %>
    <%= f.label 'Female', inline: true, checked: true  %>
    <%= f.radio_button :gender, 0  %>
    <%= f.label 'Male', inline: true  %>
  <% end %>

Tried this suggestion but still getting the same problem, only the the radio buttons are no longer in line and have incorrect formatting.

What would be the best way to fetch information of Youtube result searched by a query?

This gem yourub is not compatible with fetching particular page of the result set(pagination)

Is there any other way to fetch data sets of the Youtube result searcged by a query?

I'd like to select the page number of the result set, and the maximum number of the records to show in one query.

Passing parameter to partial view - Rails 4/postgresql/json

I have a Deal model with a column/attribute called 'deal_info' which is a json column.

It looks like this for example

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

On my view deal.html.erb, i have:

<%= for deal_nb in 0..@deal.number_of_deals do %>
  <div class="modal fade" id="myInfoModal<%= modal_nb %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <!-- render the right modal type -->
    <%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: deal_nb  %>
  </div>
<% end %>

Above, as you see above, I'd like to pass for each iteration of the loop inside parameter_i_want_to_pass the number of the iteration loop (2nd iteration would be parameter_i_want_to_pass= 2 for example).

On the partial I have:

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">this is mt4</h4>
    </div>
    <div class="modal-body">
      this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]['text1'] %> 

    </div>
  </div>

I get the following error:

no implicit conversion of String into Integer (on line "this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]")

Actually I even tried to detect more easily the bug by just passing a set number instead of the variable 'deal_nb'

<%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: 2  %>

But I still get exactly the same error.

Prevent foreman to crash when typo in code

I am using foreman gem on my Rails project to handle the different processes to be launched at startup (web, mailer, delayed job, ...).

It's working as expected but if I save a file with a typo or try to access a property on a nil object, foreman crash for all processes. I have to manually kill each ruby and node (for maildev) processes in order to run foreman start again.

Is there a way to prevent foreman to crash as the plumber plugin for gulp tasks ?

Thanks !

My project:

  • Rails 4.2
  • Ruby 2.2.0
  • Foreman
  • Server Unicorn
  • Mac OSX

Capybara undefined model method, not if I run the test myself

Here's my Rspec/Capybara code

visit new_user_registration_path
page.fill_in 'Email', with: 'manager@test.com'
page.fill_in 'Password (8 characters minimum)', with: 'Password'
page.fill_in 'Password confirmation', with: 'Password'
page.fill_in 'Promo code', with: "test100"
page.click_button "Sign up"

It returns this error:

1) Sign up Sign in with promo code when new user signs up with 100% promo
     Failure/Error: page.click_button "Sign up"
     NoMethodError:
       undefined method `active=' for #<Subscription:0x007f9b5f868c68>
     # ./app/models/subscription.rb:24:in `activate'
     # ./app/models/subscription.rb:17:in `setup'
     # ./app/controllers/users/registrations_controller.rb:37:in `create'
     # ./spec/integration/signup_spec.rb:18:in `block (3 levels) in <top (required)>'

However if I manually enter the info to sign up there's no error:

Here is the model code.

  def setup
    if has_full_discount?
      activate
    elsif create_stripe_customer and charge_stripe_customer
      activate
    end
  end

  def activate
    self.update_attribute(:active, true)
  end

Cancancan ability for specific case

I use cancancan gem for role based authorization rules. I need to preform something like:

can :read, Post, Post.status = 1

This means that user can read post with status = 1. How can i do that?

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

"daily":{"summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.","icon":"rain","data":[{"time":1435464000,"precipProbability":0.99}]}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time "1435464000". Any suggestion on how to complete my current JSON parsing "query"?

What's the correct way to reference a helper in a rails controller?

Sometimes I need to use helper methods in controllers (sanitization methods, rendering text back to the view, various other applications). What's the right way? I've got:

  • self.class.helpers.myhelper
  • view_context.myhelper
  • include MyHelper; myhelper
  • helper MyHelper; myhelper

Rails posting to a custom action on a nested polymorphic resource

I am unable to get the "like" action to work.

I am basing my action on the Raiscast no 364:

http://ift.tt/NbOPyK

I believe my problem lies with the route:

resources :polls do
  resources :likes, only: [], defaults => { :likeable => 'poll' } do
    member { post :like }
  end    
end

Has defined the following route:

like_poll_like POST   /polls/:poll_id/likes/:id/like(.:format)             likes#like {:likeable=>"poll"}

I see here that the route is looking for an id for both the poll and the like however the controller action is to create a new row for in the likes table for the poll so there is no id for the like.

My like controller is:

class LikesController < ApplicationController
  before_filter :load_likeable

  def like
    like = @likeable.likes.new(value: params[:value], user_id: current_user)
    if like.save
      redirect_to :back, notice: "Thank you for voting."
    else
      redirect_to :back, alert: "Unable to vote, perhaps you already did."
    end
  end

  private

    def like_params
      params.require(:like).permit(:value)
    end

    def load_likeable
      resource, id = request.path.split('/')[3,4]
      @likeable = resource.singularize.classify.constantize.find(id)
    end

    def likeable_id
      params[(params[:likeable].singularize + "_id").to_sym]
    end

  end

Here is the helper I am unable to get to work:

<%= link_to "Click here", polymorphic_url(poll, action: :like, value: 1), method: "post" %> to vote for <%= poll.option %>

This returns the following error:

undefined method `like_poll_url' for #<#<Class:0x007f4dbf3d4668>:0x007f4dbf308ba8>

I do not want to move the like action into the polls controller as likes is polymorphic and the same functionality will be reused.

Rails I18n :many :other :count problems

I often have problems with translations. I remember this had to do with some translations using :many, but yet when I see an error message like this

translation data {:one=>"1 month", :other=>"%{count} months"} can not be used with :count => 3

...it shouldn't make any sense, isn't :other supposed to handle all other cases ??

EDIT for the english version, I'm using the default english files, so in this particular case, this one

Is it necessary to use embedded Ruby in Rails?

I'm learning The Ruby on Rails Tutorial and currently going through the sections on embedded Ruby for the html (.html.erb) files. Is it necessary to use embedded Ruby in the html files? Are there major advantages besides code reusability? I'm trying to simply the learning process as much as I can and I'd like to skip the embedded Ruby/html parts if possible.

Concerns about using Devise with Angular

I have a Rails application that is using Devise for authentication and Angular on it's fontent to have a SPA application.

Now currently what I do is that when the user first loads the page, the user gets served a static html page with some angular on it. User can enter the credentials there and then press button to log in.

Now when the user logs in successfully then server will redirect the user back on the index page, but now I check on html page that current_user exists and then render and div that has ng-view in it. From here on every page change is done with ng-route and every request to the server is done with Angular.

Now as I understand, as long as the client making Ajax requests is under the same domain then the session cookies will be sent also along with requests. So technically the user should be checked on every request and all should be fine?

But is this a good way of handling the whole situation? Also what will happen when I later want some mobile apps to also be able to log in into that server and fetch some info form there?

Placing a bang before an instance variable - !@my_var

The logged_in? method in the code doesn't use the @ sign to reference the current_user instance variable, does this mean that the variable is local to the logged_in? method or does it still reference the @current_user variable? I noticed if I write !@current_user instead of !current_user the method doesn't work correctly. I am slightly confused how this is working under the hood because would if I had a local variable in logged_in? named current_user and I did not want it to reference the @current_user instance variable above.

def current_user
    @current_user ||= User.find_by(id: session[:user_id])
end

def logged_in?
    !current_user.nil?
end

Pass custom data while subscribing and use it while publishing to a channel - private_pub

I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.

Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.

Following js file is executed when a new message is created.

<% publish_to conversation_messages_path(@conversation.id) do %>
    $("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
    $("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);

The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?

This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.

One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.

Rails test and ActiveRecord in routes.rb

I would like to know how I could use ActiveRecord in the routes.rb file on my Rails application.

I am creating some optional modules which can be enabled or disabled dynamically. I don't want the routes to exists if the module is disabled so I created a condition around the optional routes. In development it's work properly but in the test environment, my query returns nil even if my fixtures are properly settled.

How can I make tests to use my fixtures when I am using OptionalModule.all ?

Thanks !

Here is my routes.rb file:

Rails.application.routes.draw do
  optional_modules = OptionalModule.all # this returns nil in test mode

  # by_name is a scope defined in the model
  if optional_modules.by_name('GuestBook').enabled?
    get 'toggle_guest_book_validated/:id', to: 'admin/guest_books#toggle_guest_book_validated', as: :toggle_guest_book_validated
  end
end

My fixtures:

guest_book:
  name: GuestBook
  enabled: true

My project:

  • Rails 4.2
  • Ruby 2.2.0

ruby on rails install mysql2 but not show

I know may be this is a popular problem but i try many solutions and not get to finish

I try to install mysql in rails with

gem install mysql2

And I get the result

Building native extensions.  This could take a while...
Successfully installed mysql2-0.3.18
1 gem installed

But when i try to execute the command

bundle show mysql2

I get

Could not find gem 'mysql2'.

All these command execute in my application root directory

What is the problem ?

Rails Simple Form Country Select

I am trying to make an app with Rails and Simple Form with country_select.

I am getting an error that says:

wrong number of arguments (4 for 0)

I am using the example that i found, for simple form on the country select gem documentation page. I don't understand what's going wrong.

In my model I have:

     geocoded_by :address
  after_validation :geocode, if: ->(obj){ @obj.address.present? and @obj.address_changed? }


  def address
    [city, state, participation_country].compact.join(', ')
  end

In my form I have:

 <%= f.simple_fields_for :scope do |participants_s| %>
      <%= participants_s.simple_fields_for :participant do |par| %>
<%= par.select :participation_country,
                           priority: ["AU", "GB", "NZ", "US"],
                           selected: :participation_country,
                          label: false,
                          prompt: "Select participation country" %>

In my view I have:

<%= @project.scope.participant.address %>

Can anyone see what I have done wrong in trying to set this up? The error message indicates the problematic line is:

<%= par.select :participation_country,

I can't count 4 of anything except suggested country codes, although I deleted one of those to try and I get the same error.

CanCanCan is not blocking access for users index page

I want to stop users who aren't logged in from accessing the URL using CanCanCan

http://localhost:3000/users

My Ability model is

class Ability
include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    elsif user.roles.size > 0
      can :manage, User, :id => user.id
    else
      can :read, :all
      cannot :read, :User
    end
  end
end

And my Users controller is

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.paginate(page: params[:page],:per_page => 5)
  end

  def new
    # @user = User.new
  end

  ...
end

When I access the page as an guest user. I see the users index page instead of being redirected to login by this code in my application controller

rescue_from CanCan::AccessDenied do |exception|
  if user_signed_in?
    flash[:error] = "Access denied!"
    redirect_to root_url
  else
    flash[:error] = "Please Sign in"
    redirect_to new_user_session_path
  end
end

CanCanCan works and stops access to the other actions in the controller just not for index.

How to display error messages in a multi-model form with transaction?

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.

How should I adjust the code below so that also the error messages for user get displayed?

def new
  @organization = Organization.new
  @user = @organization.users.build
end

def create
  @organization = Organization.new(new_params.except(:users_attributes))
  #Validations require the organization to be saved before user, as user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.

  @organization.transaction do
    if @organization.valid?
        @organization.save
        begin
          # Execute next line in debugger (with invalid user info) correctly responds with: ActiveRecord::RecordInvalid Exception: Validation failed: Email can't be blank, Email is invalid, Username can't be blank, etc.
          @organization.users.create!(users_attributes)
        rescue
          # Should I perhaps add some line here that adds the users errors to the memory?
          raise ActiveRecord::Rollback
        end
     end
  end

  if @organization.persisted?
    flash[:success] = "Yeah!"
    redirect_to root_url
  else
    @user = @organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
    render :new
  end

end

The form view includes:

<%= form_for @organization, url: next_url do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <%= f.text_field :name %>
        # Other fields

    <%= f.fields_for :users do |p| %>
        <%= p.email_field :email %>
            # Other fields
    <% end %>

    <%= f.submit "Submit" %>
<% end %>

The error messages partial is as follows:

<% object.errors.full_messages.each do |msg| %>
  <li><%= msg.html_safe %></li>
<% end %>

Update: Following the steps from Rob below I arrived at an errors partial below. This still does not display error messages for User. I added debugger responses inside the code below and for some reason nested_model.errors.any? returns false, while the debugger inside the controller (see above) does return error messages for user.

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>

    <ul>
      <% object.errors.full_messages.each do |msg| %>
        <li><%= msg.html_safe %></li>
      <% end %>
    </ul>

  </div>
<% end %>

<% if defined?(nested_models) && nested_models.any? %>
  # Debugger: responds with "local-variable" for "defined?(nested_models)" and for "nested_models.any?" returns true.
  <div id="error_explanation">
    <ul>
      <% nested_models.each do |nested_model| %>
      # Debugger: "nested_model" has the same values as "nested_models.any?", as you would expect. But for "nested_model.errors.any?" it returns false, which it shouldn't.
        <% if nested_model.errors.any? %>    #Initially had "unless nested_model.valid?" but then errors for User are immediately displayed on loading the form page (new method).
          <ul>
            <% nested_model.errors.full_messages.each do |msg| %>
              <li><%= msg.html_safe %></li>
            <% end %>
          </ul>
        <% end %>
      <% end %>
    </ul>
  </div>
<% end %>

How to use a proc to format groupdate keys?

I'm trying to understand how the format option works in the groupdate gem.

The readme explains that format takes a string that is passed to strftime or a proc (here).

I'm having trouble understanding the proc part of this.

A simple example, if User.group_by_month(:created_at).count.keys returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] (i.e., months of the year), how would I do a simple transformation of these keys, say key * 2?

Looking at the source, format appears to be expecting a method

if options[:format].respond_to?(:call)
  options[:format]
end

So I would have expected to be able to do something like User.group_by_month(:created_at, format: 'Proc.new { |d| d * 2 }')....

But this returns only Proc.new { |d| d * 2} as a string.

What am I doing wrong?

Slim ignoring class & style on f.select field?

I'm sure I'm being blind, can you spot something I've missed:

= f.select :region, options_for_select(YAML.load_file("#{Rails.root}/config/regions.yml").collect{|x| [x[1]['name'], x[0]]}), class: "form-control", style: 'display:none;'

Slim just ignores the class & style statements, but everything else looks fine. What am I doing wrong? (rails 4).

Ruby: how to parse string '3 days ago'?

Given an input string like 3 days ago, how can I turn it into a date attribute? Maybe something like DateTime.parse('3 days ago')?

ActiveRecord::Base.establish_connection with postgresql on AWS

When got my database.yml configured like this:

default: &default
  adapter: postgresql
  encoding: utf8
  pool: 5
  timeout: 5000

production:
  <<: *default
  host: my_db_address
  port: 5432
  database: my_db_name
  username: my_db_user_name
  password: my_db_password

< test and development ommited >

When I establish connection like this:

ActiveRecord::Base.establish_connection

it says ActiveRecord::AdapterNotSpecified - 'production'

It works hovewer If I do it like this: ActiveRecord::Base.establish_connection( {:adapter => 'postgresql', :database => 'my_db_name', :host => 'my_db_address', :port => '5432', :username => 'my_db_user_name', :password => 'my_db_password'} )

I'd rather load the config from database.yml. How do I do this?

I'm on Rails 4.2.1 and Postgres 9.4

HAML/CoffeScript vs HTML/JavaScript for React on Rails

I want to use React with Rails. I already know html/JS, Begineer at Rails and just finished some tutorials on official site on React. Now I want to lear to use React with Rails. I noticed that many tutorials are using haml + coffescript. After researching on those two I found that they make developing easier and code more readable. But some people say that they generate bad html and JavaScript.

Is haml + coffescript worth learning for using them with React on Rails.

One of the reasons why I am not sure whether to use or not hamls/coffescript is that official documentation for React is written for Javascript.

how to save class as one of attribute in ROR model

so here is very small help i need for ROR , since i m a newbie in rails community. i m trying to create a model in rails named chat where i have two columns user1 and user2 , i want to store the user object in these. in grails i do this simply as

               class Chat {
                    User user1
                    User user2
                    Date chatStartedOn
                 }

and i m done , i did somewhat same for rails

        rails generate model Chat user1:User user2:User chatStartedOn:date                    

but i run db:migrate it showing me the error

            undefined method `User' for #<ActiveRecord::ConnectionAdapters::TableDefinition

my user migrate file

              class CreateUsers < ActiveRecord::Migration
                def change
                 create_table :users do |t|
                    t.string :username 
                    t.string :email
                    t.string :encrypted_password 
                    t.string :salt
                    t.timestamps
                   end
                end 
                end

Please guide how do i save users object in chat table.. help !

Why Paperclip makes a request when asked for url?

sc.image.url(:thumb)

What I see then in the logs:

[AWS S3 200 0.601484 0 retries] head_object(:bucket_name=>"****",:key=>"sc/images/000/000/526/original/file.jpg")

Why Paperclip does this request? It seems that it checks if the file still exists on the sever before giving the url, to avoid giving the broken ones.

Is there a way to stop it from doing the check so it simply returns the url without doing additional requests?

Rails how to create recursive nested_form_for for child-parent relations

Model is

class MenuItem < ActiveRecord::Base
  belongs_to :menu_item
  has_many :menu_items
  accepts_nested_attributes_for :menu_items
end

How to create a form with ability to add dynamically children and also children of children if needed (preferably with nested_form_for). In other words form shall be something like:

input
  child input
    child input (child of child)
    add/remove child (child of child of child)
  add/remove child (child)
add/remove input

Clicking add/remove will add/remove one more according child, how can I achieve this?

With Nested Resources in routes.rb with custom to_param, how can Strong Parameters allow created/update to permit?

I can't find something that'll lead in the right direction. Everyone else's similar issues with nested resources seems to resolve around accepts_nested_attributes_for… which I'm not trying to do. I'm not trying to save children from the parent, I'm trying to save directly from the child.

In my routes.rb, I have nested my resource

resources :parents, param: :parent do
  resources :children, param: :child
end

parent and child tables both have their own id column, but also have unique index on columns parent and child respectively, which I was to be used in the URL instead of the id.

http://ift.tt/1BJQ9Em

This is working fine browsing around going to the show, edit and index actions of each controller.

The problem is there are exceptions saving data.

I'm hoping the root-cause of the issue doesn't come down to a field in the child table is also called child as that's what I've used to override to_param in the model and need to keep it that way.

Navigating to the edit screen: http://ift.tt/1HoWN5u and pushing submit on the form, returns this NoMethodError exception:

NoMethodError at /parents/harry/children/sally
undefined method `permit' for "sally":String

I'm sure the problem is something to do with how my Strong Parameters line is in children_controller.rb. Can I add to require a hash of :parent and :child maybe?

def children_params
  params.require(:child).permit(:child, :date_of_birth, :nickname)
end

Update 1 (Added params): Here are the request parameters:

{
  "utf8"=>"✓", 
  "_method"=>"patch", 
  "authenticity_token"=>"fAkBvy1pboi8TvwYh8sPDJ6n2wynbHexm/MidHruYos7AqwlKO/09kvBGyWAwbe+sy7+PFAIqKwPouIaE34usg==", 
  "child"=>"sally", 
  "commit"=>"Update Child", 
  "controller"=>"children", 
  "action"=>"update", 
  "parent_parent"=>"harry"
}

Other instance variable in-scope at time of error:

@parent

<Parent id: 1, parent: "harry", description: "", user_id: 1, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">

@child

<Child id: 1, child: "sally", date_of_birth: nil, parent_id: 1, nickname: nil, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">

Rails Searchkick / Elasticsearch has_many and belongs_to associations

Im trying to use Searchkick to run a search and return based on multiple models.

My book model contains this

class Book < ActiveRecord::Base

  searchkick

  has_many :book_subjects
  has_many :subjects, through: :book_subjects

  belongs_to :author
  belongs_to :publisher

end

and then my controller has this

def index

 if params[:search].present?
   @books = Book.search(params[:search], operator: "or")
 else
  @books = Book.all
 end
end

I want the search results to search the associated models and return any results there too -- so the boo subject name, the author and the publisher.

thanks

How to install Ruby on Rails on Windows?

I just need to know how to install ruby and rails. I am trying to do this from two days but no result. Actually I dont have any idea about this.

samedi 27 juin 2015

Rails console NameError: uninitialized constant - nested resources

I am trying to make an app with Rails 4 and simple form.

I have three models - Project, Project_Question and Project_Answer. I made all of these by generating scaffolds so all naming conventions have been followed.

My resources are nested:

resources :projects do
    resources :project_questions do
      resources :project_answers
    end
  end

I am trying to use the console to find project answers created in my testing, but when I try to search for project answers:

2.1.1p76 :001 > Project_Answer.where(:answer => [hgvbhjb]).first

I get this error message:

LoadError: Unable to autoload constant Project_Answer, expected /app/models/project_answer.rb to define it.

The other problems on this site that seem to get the same error messages appear to be where people have not named their model.rb files in the singular. I have that.

I can only think that there is an extra step required to search the console if resources are nested. Does this sound plausible? If so, are there any materials to help figure out how to search the console with nested resources?

Can anyone see what has gone wrong?

Is there a way to limit selections in the Rails FormBuilder datetime select helper?

I want to use FormBuilder's datetime_select helper to create dropdowns for a datetime field and want to specify which minute values to use in the drop down (let's say, I want to use 0, 15, 30 and 45.)

Is there some hidden option to f.datetime_select that will let me do this?

Filter ActiveAdmin with Postgresql json column on specific json keys

I have a Deal model that features a json column called deal_info. It's actually an array of JSONs.

I'm using active admin.

For example :

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

As first step now I would like to have a filter that would enable me to filter the deals based on the fact that deal_info json column includes at least one time the modal_id in one of its included json.

It would enable me in a select dropdown to choose for example modal_id = 6 and would filter the list of Deals to only show deal 1 (see example above).

One of the further challenge is that I need to be able to remove duplicates on the select dropdown in order not to have multiple times the same id: here for example i can't have select = [4,6,9,10,11,11]...each modal_id can only appear once.

I only found this but it did not work for me.

My current Active Admin Code

ActiveAdmin.register Deal do
  filter :modal_id,
  as: :select 
  collection: deal_info.all.to_a.map ???? 
end

EDIT after Andrei answer that helped move forward but not (yet) solve the problem

I added this code :

models/deal.rb

class Deal < ActiveRecord::Base
  store_accessor :deal_info, :modal_id
end

# using http://ift.tt/1LNYzLh
ransacker :modal_id do |parent|
   Arel::Nodes::InfixOperation.new('->', parent.table[:deal_info], 'modal_id')
 end

inside active admin Deal file

ActiveAdmin.register Deal do
     filter :modal_id,
     label: 'modal id',
     as: :select,
     collection: -> { Deal.all.pluck(:info_throbber).flatten.map {|el| el['modal_id'] }.uniq }

It seems to PARTLY work but not completely. Indeed it does show me on the dropdown the right various modal_id's and they are well de-duplicated BUT when I select one of them on the dropdown, and click FILTER on the right side (where the filter sidebar is), it load the whole page again WITHOUT applying the filter.

For example, on my modal_id dropdown, i have the chocie between ANY/4/5/8. If I choose modal_id 5 and click the FILTER button when the page with all the deals (that should be filtered on modal_id = 5) load, inside the sidebar modal_id select dropdown, I don't see 5 as I had chosen but ANY. The value of 5 was not "KEPT"/"REMEMBERED" and it got back to the value ANY. I don't understand why.

Web service in Rails to handle two databases

I asked in a question LINK how it was the best way to manage two databases MySQL for a Rails Web App. I searched "web services" in internet and i found a lot of things. My questions are:

1) I have to program an app in Rails, is it usefull to create the web service for this app in Rails too?

2) I have to use two databases , in my Web service how can i have to manage this?

for example, i need the list of the users of the DB1, so i write:

http://localhost:3000/users/

but how do i have to program the web service to be able to separate the two databases? I mean , if i need the users od the DB2 i would use an url like the before one:

http://localhost:3000/users/     (but for DB2)

3) I know that in a web service we should create the WSDL file. But is really necessary in my case? i will not publish the web service so , i think is not necessary to create the WSDL. is it?

Sorry for the newbie questions but it's my first time in web service programming.

Rails render partial with progress bar

I'm running Rails 4 and am trying to use a bootstrap form wizard. The thing about the form wizard is that not all of its tabs should be displayed at all times.

The form wizard is in a partial that I render via $("#tab3").html("<%= j(render partial: 'wizard' ) %>"); in update_forms.js.erb (called via an ajax call).

Everything works well in this except the progress bar doesn't display (it is 0) unless I refresh the page. Any thoughts on how I can set the progress bar when rendering the partial?

Rails 4 / Nginx - "staging database not configured"

I've never seen this error before, I don't want a staging database, but it keeps asking for it?

Message from application: 'staging' database is not configured. Available: ["default", "development", "test", "production"] (ActiveRecord::AdapterNotSpecified)

Is there a way around this?

Ordering ActiveRecord Relation by temporary column field in Rails

I need to order a query of Profile entries in an ActiveRecord::Relation object by a value that is computed on run-time.

I have created and assigned a temporary column distance in my controller for the Relation object by using attr_accessor like so:

@profiles.each do |p|
  p.class_eval do
   attr_accessor :distance
  end
end

@profiles.each do |p|
  p.distance = distance_arr[@profiles.index(p)]  # Distance values obtained from an instance array
end

However, when I try to order the Relation with the order method, I get a no such column: distance error i.e. it's not picking up the temporary field.

Here's how I tried to order it in my controller (note I'm using the will_paginate gem, but that is irrelevant).

@profiles = @profiles.order('distance ASC').paginate(page: params[:page])

create two connections MySQL on Rails project

I am creating a CRM(Customer relationship management) in Rails. I have to use two databases(MySQL).I have a doubt in the correct use of these databases.

I mean, i read on internet that is possible to open two connections in a Rails project, but is this the right way to hit the problem? is really good to open two connection in a project?

is it used?if not, what is the solution in the state of art(maybe the simpler to manage queries) for my problem?

Koala (Rails) for FQL query automatically converting GET request to POST request

I have been using Koala gem for firing FQL queries to fetch facebook data. Normally all FQL queries are GET resquests but I have seen that in facebook's Graph API explorer if the query is too long, its automatically converted to a POST request. Does the Koala gem also exhibits a similar behaviour ?

How do I render multiple lines of HTML in a helper?

I have a helper that looks like this:

if current_user.find_voted_items(vote_scope: :inspired).include?(post)
   link_to vote_inspired_post_path(post, vote_scope: :inspired), method: :post, data: { confirm: 'Are you sure this post Inspires you?' }, class: "btn btn-default" do
    "<i class='fa fa-lightbulb-o'></i> <br />Inspired".html_safe
   end
   link_to vote_happy_post_path(post, vote_scope: :happy), method: :post, data: { confirm: 'Are you sure this post makes you happy?' }, class: "btn btn-success" do
    "<i class='fa fa-smile-o'></i> <br />Happy".html_safe
   end
   link_to vote_disappointed_post_path(post, vote_scope: :disappointed), method: :post, data: { confirm: 'Are you sure this post disappointed you?' }, class: "btn btn-info" do
    "<i class='fa fa-meh-o'></i> <br />Disappointed".html_safe
   end
   link_to vote_upset_post_path(post, vote_scope: :upset), method: :post, data: { confirm: 'Are you sure this post upsets you?' }, class: "btn btn-inverse" do
    "<i class='fa fa-frown-o'></i> <br />Upset".html_safe
   end
end

I need all the links and their nested <i> tags to be rendered - but for some reason, this version is just rendering the last line.

All of that is inside a method called show_vote_buttons(post), that is being called like this in the view: <%= show_vote_buttons(@post) %>

What's the best way to tackle this?

“rails server” on existing application not working

I cloned an application, ran bundle install successfully, then tried running rails server and was met with the following error, which is basically requiring me to scaffold a rails application before using rails commands:

Usage:


 rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]                                      # Path to the Ruby binary of your choice
                                                         # Default: /Users/brianhedberg/.rbenv/versions/2.0.0-p481/bin/ruby
  -m, [--template=TEMPLATE]                              # Path to some application template (can be a filesystem path or URL)
      [--skip-gemfile], [--no-skip-gemfile]              # Don't create a Gemfile
  -B, [--skip-bundle], [--no-skip-bundle]                # Don't run bundle install
  -G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file
      [--skip-keeps], [--no-skip-keeps]                  # Skip source control .keep files
  -O, [--skip-active-record], [--no-skip-active-record]  # Skip Active Record files
  -S, [--skip-sprockets], [--no-skip-sprockets]          # Skip Sprockets files
  -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                         # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]                          # Preconfigure for selected JavaScript library
                                                         # Default: jquery
  -J, [--skip-javascript], [--no-skip-javascript]        # Skip JavaScript files
      [--dev], [--no-dev]                                # Setup the application with Gemfile pointing to your Rails checkout
      [--edge], [--no-edge]                              # Setup the application with Gemfile pointing to Rails repository
  -T, [--skip-test-unit], [--no-skip-test-unit]          # Skip Test::Unit files
      [--rc=RC]                                          # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                            # Skip loading of extra configuration options from .railsrc file

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

    You can specify extra command-line arguments to be used every time
    'rails new' runs in the .railsrc configuration file in your home directory.

    Note that the arguments specified in the .railsrc file don't affect the
    defaults values shown above in this help message.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.

vint-i-vuit in this post: "rails server" on existing working application not starting , but the suggested root of that problem was an issue with Rails 3, and I am on Rails 4.0.5.

Any ideas?

rails start create form url wrong

i flowed rails getting_started

in the 5.2 section “The first form”,the

http://localhost:3000/articles/new

success form

works fine before i add form “, url: create” how can i resolve this problem?

when i add url the result is:

enter image description here

and the rails run environment is:

➜ blog bin/rake routes

   Prefix Verb   URI Pattern                  Controller#Action

welcome_index GET /welcome/index(.:format) welcome#index

     root GET    /                            welcome#index

 articles GET    /articles(.:format)          articles#index

          POST   /articles(.:format)          articles#create

new_article GET /articles/new(.:format) articles#new

edit_article GET /articles/:id/edit(.:format) articles#edit

  article GET    /articles/:id(.:format)      articles#show

          PATCH  /articles/:id(.:format)      articles#update

          PUT    /articles/:id(.:format)      articles#update

          DELETE /articles/:id(.:format)      articles#destroy

➜ blog ruby -v

ruby 2.0.0p481 (2014-05-08 revision 45883) [x86_64-darwin13.1.0]

➜ blog sqlite3 --version

3.7.13 2012-07-17 17:46:21 65035912264e3acbced5a3e16793327f0a2f17bb

➜ blog rails --version

Rails 4.2.1

Raise error on unpermitted parameters rails

I am currently trying to implement raising an error when unpermitted parameters are posted in my RoR back-end. I included

  config.action_controller.action_on_unpermitted_parameters = :raise

in my development.rb configuration. Now, for example I have in one of my controllers:

def apiary_params
    params.require(:apiary).permit(:name, :municipality, :prefecture, :latitude, :longitude, :numberofbeehives, :notes)
end

If I now try posting another parameter lets say "apiary[asdf]" then an internal server error is raised correctly. However if I try posting a random "asdf" param not in the apiary hash, then the request is handled without an error. Does that mean that the random "asdf" and whatever other parameter not in the apiary is permitted? How can I fix that?

Serving images from S3 using Cloudfront

I have an S3 bucket where images are uploaded to. All of my static content is served via a Cloudfront distribution however, or at least it should be.

When I look at my page source, it indicates that all static content, except for the images in my S3 bucket, is served from Cloudfront. The images in S3 is still served from S3.

I have played around with my settings, but nothing seems to be fixing this issue.

Currently in my Cloudfront distribution I have the following settings:

  1. Origin Pointing to my web url (foo.herokuapp.com)
  2. Origin Pointing to my S3 Bucket:

    -Origin Domain name pointed to my S3 Bucket

    • Origin Path pointed to /uploads (This is the base directory in my S3 Bucket)
    • Restrict Bucket Access set to Yes
    • Tried setting Origin Access Identity to Create new and Setting Update Bucket policy to yes. I checked my Bucket Policy and it has created a Cloudfront Entry in there.

Any idea on what might cause this setup not to retrieve my S3 content via Cloudfront?

Using Hash syntax with 'OR' for Where clause in Rails

I know there are three main types of syntax's for the where clause:

  1. Pure String
  2. Array
  3. Hash

Specifying AND for the where clause is straight forward:

#Pure String syntax
@people= Person.where("name = 'Neil' AND age = 27")

#Array syntax
@people = Person.where(["name = ? AND age = ?", 'Neil', 27])

#Hash syntax
@people = Person.where({name: "Neil", age: 27})

Specifying OR for this same where clause is stumping me for the hash syntax. Is it possible?

#Pure String syntax
@people= Person.where("name = 'Neil' OR age = 27")

#Array syntax
@people = Person.where(["name = ? OR age = ?", 'Neil', 27])

#Hash syntax DOESN'T WORK
@people = Person.where({name: "Neil" OR age: 27})

How do I test fulltext fields using sunspot_matchers in rspec?

My search controller does this:

search = Sunspot.search(Item) do
  fulltext params[:q] do
    fields(:foo, :bar, :bletch)
  end
end

And in my rspec controller test I have the following:

get :show, :q => q

expect(Sunspot.session).to have_search_params(:fulltext, q, proc do
  fields(:foo, :bar, :bletch)
end)

Side note: when I tried using a block instead of a proc, the block was never executed:

have_search_params(:fulltext, q) do
  # This block was never executed
end

My support/sunspot.rb contains only the following:

Sunspot.session = SunspotMatchers::SunspotSessionSpy.new(Sunspot.session)

When I run the test, I get the following error:

  1) SearchController GET search when a user runs a search performs a fulltext search on the right fields
     Failure/Error: fields(:foo, :bar, :bletch)
     NoMethodError:
       undefined method `fields' for #<Sunspot::DSL::Search:0x007fa0f0da0168>
     # ./spec/controllers/search_controller_spec.rb:28:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/search_controller_spec.rb:27:in `block (4 levels) in <top (required)>'

What's the right way to test that my controller is supplying the correct params when doing a fulltext search? Google yields no relevant results when querying this problem.

vendredi 29 mai 2015

Submitting post between ajax and php

I'm a newbie in the world of php and I was trying to learn it with a simple page. I've created an html form and I want to send data using ajax but it still POST http://localhost/Home.php 500 (Internal Server Error)

In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)

This is my form (Home.php)

<div id="displayForm">

<form method="post" id="selectForm">
        <?php
        include ("Database.php");

        $Database = new Database( "localhost", "root", "1234");
        $Database->connectToServer();
        $Database->connectToDatabase("test");
        $Tables = $Database->countTable();
        foreach($Tables as $column) {
            echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " .  $column;
        }
        ?>
    <input type="submit" class="submit" name="createSelect">
</form> </div>

The php in the form is only for create the button with the name of the tables.

In the same file (Home.php)

<?php
 include 'ChromePhp.php';
 ChromePhp::log("corretto");
echo "ok";
?>

In the file Home.php, in the head section I've included all jquery library and the js file

<script src='jquery-1.10.2.min.js'></script>
<script src='Script.js'></script>

And this is my ajax file

$(document).ready(
    function() {
        $("#createTable").click(goCreate);
        $("#displayTable").click(goDisplay);
        $('#selectForm').submit(goSelect);
        $("#createForm").hide();
        $("#displayForm").hide();
    }
);

function goCreate(data) {
    $("#createForm").show();
    $("#functions").hide();
}

function goDisplay(data) {
    $("#displayForm").show();
    $("#functions").hide();
}

function goSelect() {
    var selectedTable = $("#selectQuery:checked").val();
    console.log($("#selectQuery:checked").val());


    $.ajax({
        url: "Home.php",
        type: "POST",
        dataType: "html",
        data: {
            'select': 'display',
            'table': selectedTable
        },
        success: function(msg) {
            console.log(msg);
        },
        error: function(xhr, desc, err) {
            console.log("error");
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }

    }); // end ajax call
    return false;
};

How do I update the location field when I chnge the latitude, longitude coordinates manually?

I am using jquery location picker plugin to take the entry of user's location through a map.

The problem that I 'm facing is that when I change the lat, long coodinates manually, the location field does not shift accordingly to the correct position however the marker does.

What is the solution?

Here is the map that I'm using http://ift.tt/1HAeglQ

extract vimeo video id from the url

Though this question is available on SO, I am facing a little problem.I failed to extract the vimeo id using vimeo regex used here: Vimeo Regex

My codes I,m using now:

function vimeoProcess(url){
   var vimeoReg = /https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/;
   var match = url.match(vimeoReg);
   if (match){
      console.log(match[3]);
   }else{
      return "<span class='error'>error</span>";
   }
}

It does not consoles any thing. Can any one help?

JQgrid file upload with form edit

I have JQgrid with form edit.

 jQuery("#tblPriceListUpload").jqGrid({
        url: $('#tblPriceListUpload').attr("RequestUrl"),
        postData: { PriceListType: SelectedPriceListType },
        datatype: "json",
        mtype: "Get",
        hoverrows: false,
        ajaxGridOptions: { timeout: 30000 },
        colNames: PriceListColName,
        colModel: PriceListColModel,
        cmTemplate: { editable: true },
        rowNum: 10,
        hidegrid: false,
        rownumbers: true,
        pager: '#PriceListGridPager',
        viewrecords: true,
        caption: "Price List ",
        height: 'auto',
        scrollOffset: 0,
        gridview: true,
        shrinkToFit: true,
        autoencode: true,
        loadonce: true,
        ignoreCase: true,
        enableClear: true,
        width: '1000',
        beforeRequest: function () {

            //responsive_jqgrid($(".jqGrid"));
        }
    });

    $('#tblPriceListUpload').jqGrid('filterToolbar', { searchOnEnter: false, enableClear: false, defaultSearch: "cn", stringResult: true });

For Form Add

  $("#tblPriceListUpload").jqGrid('navGrid', '#PriceListGridPager',
           { edit: true, add: true, del: true, refresh: true, view: false, search: false },
           { //Edit Code here
               }, {

               caption: "",
               title: "Add Attachment",
               id: "add_Attachment",
               buttonicon: "ui-icon-plus",
               position: "first",
               url: 'AddPriceList',
               recreateForm: true,
               onclickSubmit: function (response, postdata) {
                   debugger;
                   if (jqXHRData) {
                       //jqXHRData.submit();
                       $("#Form").submit();
                       $("#FormError").remove();

                   }
               },
               beforeShowForm: function (form) {
                   $("#PriceListType").val(SelectedPriceListType);
                   $("#tr_PriceListType").hide();
                   $('#FileName').fileupload({
                       replaceFileInput: false,
                       dataType: 'json',
                       url: 'AddPriceList',
                       change: function (e, data) { },
                       add: function (e, data) {
                           jqXHRData = data
                       },
                       done: function (event, data) {

                           alert(data.result.message)
                           $("#cData").trigger('click');
                           $("#tblPriceListUpload").setGridParam({ datatype: 'json', page: 1 }).trigger("reloadGrid");
                           jqXHRData = null;
                       },
                       fail: function (event, data) {

                           if (data.files[0].error) {
                               alert(data.files[0].error);
                           }
                       }
                   });
               }

           }, {});

And Col Model Below

     var PriceListColModel = [{ name: 'DisplayDescription', index: 'DisplayDescription', align: 'center', editable: true, },
           {
               name: 'Header', index: 'Header', width: 95, align: 'center', formatter: 'select', editable: true,
               edittype: 'select', editoptions: { value: HeaderList, defaultValue: 'HP Oct 12 - GOs' },
               stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + HeaderList }
           },

    {
        name: 'OneSeriesPerPage', index: 'OneSeriesPerPage', align: 'center', formatter: 'checkbox', edittype: 'checkbox',
        editoptions: { value: "true:false", defaultValue: "true" }, editable: true
    },
{
    name: 'EnvironmentCode', index: 'EnvironmentCode', search: true, editable: true,
    edittype: 'select', editoptions: { value: EnvList, defaultValue: 'AFI' },
    stype: 'select', searchoptions: { sopt: ['eq', 'ne'], value: ':All;' + EnvList }
},
{
    name: 'FileName', index: 'FileName', edittype: 'file', editable: true,
    edittype: 'file',
    editoptions: {
        enctype: "multipart/form-data"
    }, search: true
},
    {
        name: 'PriceListType', index: 'PriceListType', align: 'center', hidden: true, editrules: {
            required: true,
            edithidden: true
        }
    }];

In "OnclickSubmit" event of "AddPriceList" if i am posting jqXHRData.submit(); If Check Box column is false it is not sending the data to controller. If true, it is sending the data to controller.

If i am posting the form $("#Form").submit(); I am not getting the file in Controller.

Please help on this issue.

Chomsky Normal Form using JavaScript : Stuck

I have been trying to implement a web application that converts the given context free grammar into its Chomsky Normal Form (CNF). The CodePen link to the same is http://ift.tt/1HAeeud

The only region where I am stuck is breaking down the rules of form S -> aAb into further nonterminals and terminals. Can anyone help me with an implementation algorithm regarding the same?

Track JS CSS Asset Errors on page load

Is it possible to track the number of errors and warning thrown by a browser on page load using javascript?

For example CSS Assets missing or images missing or js script errors? I don't need a detailed log but maybe a count of each type of error.

Like a count of CSS, Assets missing and JS Errors?

This needs to be tracked using JS.

Testing functionality based on HTML5 DOM-methods

I'm wondering how to test functionality based on HTML5 DOM-methods. Like the new dialog-API for example.

Consider the following function;

function show(dialog)
{
    if(typeof(dialog.showModal) !== "function")
        throw new Error("Update your browser");
    dialog.showModal();
}

I want to make sure that

  1. an error is thrown when the method is not available
  2. dialog.showModal is called if available

I'm currently running karma + jasmine with the firefox and chrome launchers but none of them seems to support the dialog-API.

Can I shim this in some kind of way? Can I create a function on all dialog DOM nodes?

I could do the following

var modal = document.createElement("dialog");
Object.defineProperty(modal, "showModal", {
    value: function()
    {
        console.log("hello world!");
    }
});

however, that isn't carried over to other instances of a dialog.

This is a very simplified example of what I'm trying to achieve.

Creating and returning object from function: can this avoid garbage collection?

If I have a function that creates an object, do some stuff and than returns it. If it's true that objects are passed by reference, does this mean that the function that creates the object (or the function's scope chain) will not be available for garbage collection?

Example code:

function convertArrayToObj(array){
   var newObj = {};
   array.forEach(function(item, index){
      newObj[index] = item;
   });
   return newObj;
}

I hope I made my doubt clear

Selecting all check boxes when only clicking one

enter image description here

How can I select all the check boxes on single click, while every check box has unique name using JavaScript? Please provide code.

 </div><!-- /.box-header -->
 <div class="box-body">
 <form name="permissionfrm" method="post" id="permissionfrm">
 <input type="hidden" name="permission" id="permission" value="assignpermission" />
  <table id="example1" class="table table-bordered table-striped">
    <thead>
     <tr>
      <th>Give All Permissions
      </th><td><input type="checkbox" name="addadmin" id="addadmin" value="Check All" onClick="this.value=check(this.form.list)"/></td>
      </tr>
      <tr>
        <th>Add</th>
        <th>Edit</th>
        <th>View</th>
        <th>Delete</th>
      </tr>
     </thead>
    <tbody>

Can Bower give conflict in my code?

If Bower update my code automatically, Can I get conflicts? It's possible my code was decrepitated. I think so. Maybe Bower Could be a problem in a proyect. How manage this problem?

Cheers!

Timing and speed of multiple sliding divs

Please see this fiddle I have set up.

You are first confronted by three links. Each link triggers divs to slide out.

  1. The link 'john smith' slides out and in at the speed we want. When it slides out the first line slides out then when that is completed the second line slides down as though coming from the first. When it slides back it does the same motion at the same speed but reverse i.e.. the second line slide back up first and then when that is completed the first line slides back to the left.

  2. When you click on the work link and menu slides out in the same manner as the bio. Also there is a sub menu that slides out when on clicks on item 2.

  3. When the user clicks on the contact link one line slides out.

What we need to achieve is this; when any div is open and another link is clicked on, the visible div slides back in reverse to how they slid in. We have almost achieve this, however, the code is not quite right as the divs are not sliding back in at the same speed and in the right order, they simply slide back fast. For example, if one has clicked on 'work' and the 'item 2' link, and then you select 'contact' the opened div slide back very quickly. What I need to achieve is that they slide back in reverse to how they slid out.

I know this sounds very complicated and if I can answer any questions to make it clearer I will.

Thanks

$('#bio-line-1').animate({width: 'hide'});
$('#contact-info').animate({right: 'hide'});
$('#bio-line-2').slideUp("fast");
$('#black-div, #black-credits, #igna-1-div, #igna-1-credits, #igna-2- div, #igna-2-credits, #fatal-div, #fatal-credits').fadeOut('100');

});

Sum Array push values, before a 0 javascript

I'm trying to take the value of an input and keep it in an array. I want to detect when the user text 0, and I want to sum all the values in the array before the 0.

Here is my code:

<form id="demo">
    <input type="number" id="lala">
    <button onclick='funsuma(this.form.lala.value)' > NO <button/>
</form> 

<script>
    var global = [];
    var suma = 0;

    function funsuma(valor) {
        global.push(valor);
        for (i = 0; i < global.length; i++) {
            if (global[i] == 0) {
                suma += parseInt(global[i], 10);
                alert("Es 0, tu suma es: " + suma);
                return false;
            } else {
                //alert(global[i]);
                document.getElementById("demo").innerHTML = "<input type='number' id='lala'> <button value='Envia' onclick='funsuma(this.form.lala.value)'> NO <button/>";
                return false;
            }   
        }

        //console.log("global");
    }
</script>

I need to popup different html pages for different url in chrome extension

For example if someone is on google.com I need to popup a different page and if someone is on xyz.com I need to pop a different page. Is that possible?

Javascript sort() array of mixed data type

If I have an array like:

["23", "765", "sfasf", "2.3E-3", "2.3cE-3"]

How can I order it so numbers(decimals, floats or scientific notation) are ordered ascending and after those strings that aren't numbers(for example "sfasf" or "2.3cE-3")?

Expected order of the example array:

["2.3E-3", "23", "765", "2.3cE-3", "sfasf"]

slick slider not initializing in Internet Explorer 8

This is the code I have, any reason why this might be? It's just not initalising.

<div class="slider-banner slick-slider">
    <div class="slide1 slide slick-slide">
        ...
    </div> 
    <div class="slide2 slide slick-slide"></div> 
    ...

    <script src="http://ift.tt/1h847p1"></script>
    <script src="../scripts/slick.min.js"></script>

$('.slider-banner').slick({ 
    dots: false,
    infinite: true,
    speed: 600,
    mobileFirst: true,
    slidesToShow: 3,
    slidesToScroll: 3,        
    onInit: function() {
        $('.slider-banner').addClass("loaded");
    },
    responsive: [{
        breakpoint: 1280,
        settings: {
            slidesToShow: 5,
            slidesToScroll: 1,
        }
    }, {
        breakpoint: 1600,
        settings: {
            slidesToShow: 7,
            slidesToScroll: 1,
        }
    }]
});

Using javascript's date.toISOString and ignore timezone

I want to use the javascript's toISOString() function and ignore the timezone.

var someDate; // contains "Tue May 26 2015 14:00:00 GMT+0100 (Hora de Verão de GMT)"
dateIWant = someDate.toISOString(); // turns out "2015-05-26T13:00:00.000Z"

The date to convert is Tue May 26 2015 14:00:00 GMT+0100 (Hora de Verão de GMT) but the converted date is 2015-05-26T13:00:00.000Z.

So, I need the date in the yyyy-MM-ddTHH:mm:ss:msZ but as you can see above it applies the timezone and changes the hour from 14 to 13.

How to achieve this?

How to improve Gulp task performance with gulp-sass plugin?

I have a sass file with long loop (generate about 800 lines of CSS) that compiles about 25 seconds. It's too long.

How can I minimize compile time?

Thanks!

How to check if changes to innerHTML have completely loaded

I'm changing the content of a div via javascript using myDiv.innerHTML = xmlHttp.responseText. xmlHttp.responseText might contain a few images which will be loaded after the div's innerHTML has been changed.

Is there any event which is fired on the div, document or window after those images have completed loading ie after innerHTML of an element has completely loaded?

Collapse row on mouse click

I found one very good example of Collapsible Content on Internet but it's unfinished.

<div class="container faq_wrapper">
    <div class="row">
        <div class="span10 offset1">
            <p>
                &nbsp;</p>
            <div class="faq-all-actions">
                <a class="faq-expand" onclick="jQuery('.answer-wrapper').css('display','block');">Expand All</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a class="faq-collapse" onclick="jQuery('.answer-wrapper').css('display','none');">Collapse All</a></div>
        </div>
    </div>
    <div class="row">
        <div class="span10 offset1">
            <div class="question-wrapper">
                <div class="arrow">
                    &nbsp;</div>
                <div class="big-q">
                    Q</div>
                <div class="question">
                    <h6>Can I try the software before I buy it?</div></h6>
                <div class="answer-wrapper">
                    <div class="big-a">
                        A</div>
                    <div class="answer">
                        Yes! Simply <a href="/trial">download a free trial</a> and you&#39;ll have instant access to all features for 30 days, absolutely free. We don&#39;t require your credit card details or any commitment.</div>
                </div>
            </div>    
        </div>
    </div>
</div>

How I can expand or hide the answer from the example when I click on the row?

Finding text within Javascript

I'm creating some functions to highlight words on a page.

The way the code works is to take the innerHTML when the page loads, and store this in memory.

I then take a copy of innerHTML - I then find the search words on the copy of innerHTML page, and wrap them with <span id="find-iteration"> tags and replace the contents of the page with the copy of innerHTML. Then, when the user re-hits the search button, I revert the page back to the original innerHTML

How to do I find text (website copy) only words and note words used as values in HTML elements/attributes.

Example, Consider the following code

 <div class="search">This is the search box</div>

Now, I want to perform a search for the word "search". The issue is, it will find it twice.

Without using regular expressions, and only using JavaScript (no jQuery please), how can I detect if the string is part of the HTML tag or not?