mercredi 31 août 2016

rails struggle to make nested form work

i have 3 models,

the relationship between those models is many to many relationship.

unit model

  has_many :unitrentperiods, inverse_of: :unit
  has_many :rentperiods, :through => :unitrentperiods

unitrentperiod model

   belongs_to :unit
   belongs_to :rentperiod

rentperiod model

   has_many :unitrentperiods, inverse_of: :rentperiod
   has_many :units, :through => :unitrentperiods

and i have a unit form, where i can create a new unit or edit an unit. i want to make my unit form not just able to manage my unit but able to manage my "unitrentperiod" as well, so lets say i have 2 rent periods like

"6 months"
"12 months"

i want my unit form to display those rent periods also with price input, so when i save my unit form, i also save 2 unitrentperiod based on rent periods in database, i did this in my view :

           <% @rentperiods.each do |rentperiod| -%>
                <tr>
                    <td><%= rentperiod.rentmonth %></td> Month
                    <td>
                          <%= f.fields_for :unitrentperiods, rentperiod.unitrentperiod.build do |element| -%>
                          <%= element.text_field :rentprice %> IDR

                          <% end -%>
                    </td>
                </tr>
          <% end -%>

somehow it's not working.

Koudoku: NoMethodError on User Model

Posting here as I'm probably missing something obvious. I'm receiving:

A NoMethodError occurred in webhook#event:

undefined method 'cancel' for #<User:0x0000000a0b7520>
  vendor/bundle/ruby/1.9.1/gems/activemodel-3.2.11/lib/active_model/attribute_methods.rb:407:in `method_missing'

The full trace is here. And the relevant block of code from stripe_event.rb is:

 events.subscribe 'customer.subscription.deleted' do |event|
    stripe_id = event.data.object['customer']
    subscription = ::Subscription.find_by_stripe_id(stripe_id)
    subscription.subscription_owner.try(:cancel)
 end

However, it looks like it's trying to call :cancel on the User model - why would it do that? Shouldn't it be trying to call it on the SubscriptionsController (here, line 131) which does have a method for :cancel?

Using Recaptcha in localhost (rails)

Iam using Google's Recaptcha in my local project which has the url localhost:3000 .

And I am using Recaptcha in the login page and it is displaying as

ERROR for site owner: Invalid site key

Is there any solution for this issue ?

enter image description here

How to configure routes for different user models using devise?

I have two different user groups, User and Flyer.

I have generated views and controllers for both the models using,

rails g devise:controllers users/flyers 

and for views:

rails g devise:views users/flyers

This is my routes.rb:

Rails.application.routes.draw do

  devise_for :flyers
  devise_for :admins
  resources :currencies
  resources :broadcasts

  devise_for :users, controllers: {
        sessions: 'users/sessions',
            registrations: 'flyers/registrations'

      }

  devise_for :flyers, controllers: {
    sessions: 'flyers/sessions',
  }
end

But I am getting error for devise for flyers controllers route:

Invalid route name, already in use: 'new_flyer_session' You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here: http://ift.tt/1g4FQcF

How can I have different routes? Thanks

Rails Associations don't work

I've read through many tutorials, and copied their code exactly, yet what they claim works for them doesn't work for me.

I'm making a most basic "has_many" and "belongs_to" association, but rails refuses to acknowledge any association whatsoever.

A user "has_many" emails. Emails "belong_to" user. Here's my code:

user.rb

class User < ActiveRecord::Base
  unloadable

  has_many :emails
  accepts_nested_attributes_for :emails,
    :allow_destroy => true,
  #  :reject_if     => :all_blank
end

email.rb

class Email < ActiveRecord::Base
  unloadable

  belongs_to :user
end

Then, in the console:

User.emails.build
NoMethodError: undefined method `emails' for #<Class:0x00000006c16e88>

Indeed, this "NoMethodError" persists no matter what.

As of now, my guess is that a capacitor in my hardware burnt out while I was installing rails, causing everything to work except this one thing. Or maybe it's something else :p

Facebook Integration with Ruby on Rails

I integrated the facebook with my Rails application . But i got Error ,

ERROR : You are not logged in: You are not logged in. Please log in and try again.

Could you please help me out i this .

Automatic state transition after certain period of time

I am using state machine gem http://ift.tt/NCaiPh.

I want to change a particular state after a certain period of time (say 2 days). Is there a way to automatically change state in background, without using job or scheduler?

Translate Log-in-Page Ruby on rails

I created the blog application from the rails tutorial with "rails new blog".

There is a page that can only be loaded when you login with your username.

The log in page is automatically generated via rails.

I want to translate the log in page.

I changed the default_locale to :de in my application.rb. It looks like this:

...

module Blog
  class Application < Rails::Application
    config.active_record.raise_in_transactional_callbacks = true
    config.i18n.default_locale = :de
  end
end

even <%= I18n.locale %> on my index page says "de".

On the log in page ther is still "password/ Sign Up /..." in English.

mardi 30 août 2016

Anyone here used Recurrence Gem?

I just found out about this gem a couple of weeks ago that exactly serves my purpose (http://ift.tt/13sogAK). Seems to work fine until I started implementing the :except feature doesn't seem to be working as intended. I did write the issue to the gem owner but seems to be inactive at the moment.

I was hoping someone has used this and fond some work around or have any suggestions. Please check the scenario below.

Scenario

r = Recurrence.new( {:interval=>3, :starts=>Wed, 31 Aug 2016, :until=>Mon, 31 Oct 2016, :except=>[Sat, 03 Sep 2016, Sun, 04 Sep 2016, Sat, 10 Sep 2016, Sun, 11 Sep 2016, Sat, 17 Sep 2016, Sun, 18 Sep 2016, Sat, 24 Sep 2016, Sun, 25 Sep 2016, Sat, 01 Oct 2016, Sun, 02 Oct 2016, Sat, 08 Oct 2016, Sun, 09 Oct 2016, Sat, 15 Oct 2016, Sun, 16 Oct 2016, Sat, 22 Oct 2016, Sun, 23 Oct 2016, Sat, 29 Oct 2016, Sun, 30 Oct 2016]})

Note: The :except dates are basically excluding all saturday and sunday.

Interval: 3 days (item should appear every 3rd day) Expected Dates: Aug 31, Sept 5, Sept 8, Sept 13

Results: Aug 31, Sept 6, Sept 9, Sept 12

If you can see, it got messed up during Sept 5 instead appearing on Sept 6.

Aug 31 is wednesday so on the 3rd day excluding sat sun should have been Sept 5.

ActiveRecord::StatementInvalid in Hr#internal_employee_page

I am learner ruby on rails,I want to join two model(tables). User.rb(users table)

class User < ActiveRecord::Base has_many :offer_letters end

OfferLetter.rb(offer_letter table)

class OfferLetter < ActiveRecord::Base belongs_to :user end

HrController(hr_controller.rb)

class HrController < ApplicationController
    def internal_employee_page
        @employees = OfferLetter.joins(:user).where(:id => :candidate_id)       
end

end

when run my code I got error "Mysql2::Error: Unknown column 'offer_letters.user_id' in 'on clause': SELECT offer_letters.* FROM offer_letters INNER JOIN users ON users.id = offer_letters.user_id WHERE offer_letters.id = NULL"

<div id="job_details">
    <% @employees.each do |emp| %>
       <%= render partial: "hr/employee_details", locals: {emp: emp} %>
    <% end %>               
</div>

Error in this line : <% @employees.each do |emp| %> So tell me where i am wrong

fetch data from db based on static set in rails

I want to fetch data from db based on static set in rails

{
data: ['data1','data2']
}

I have a data table with column values from the static data

id| Name|

1 | data1

2 | data2

3 | data3

I have another table which is related to the data table and spl_value column

id | data_id | spl_value

1  |   1     |   x

2  |   2     |   x

3  |   2     |   y

4  |   4     |   z

How do i fetch spl_value from the static data?

The expected Result is

id | Name    | spl_value

1  |   data1 |   x

2  |   data2 |   x

3  |   data3 |   y

Rails Version is 3

Rails 3.2 ruby 1.9.3 exception_notification in staging not able to send mail

I am applying exception notification gem for rails 3.2 application.

Following is my code

gemfile

gem 'exception_notification'

config/environments/staging.rb

Rails.application.config.middleware.use ExceptionNotification::Rack,  email: {
 email_prefix: '[Exception] ',
 sender_address: %('HPAE - Error' <mymail@gmail.com> ),
 exception_recipients: %w(mamail1@gmail.com)
}

It runs perfectly in my local but on server in staging its not working.

Thanks,

rails 4, ajax partial view return "gsub" error?

i have a dropdown select in my form, when i change my dropdown selection, i trigger an ajax function with script response, my goal is to dynamically load a div to display some html like "checkbox" and "image" tag based on my dropdown, so i do this :

my js :

 $(document).ready(function() 
     {


          $('#apartements_select').change(function() {



                  $.ajax({
                          url: "/units/getfloorplans",
                          data: {
                            apt_id : $('#apartements_select').val()
                          },
                          dataType: "script"
                        });


          });

    });

my controller "units/getfloorplans"

 def getfloorplans

    floorplan = Floorplan.where(:apt_id => params[:apt_id])

    @imgs = floorplan
  end

my partial js file

alert("wei");

$('#divUnitplan').append("

                                <%= escape_javascript( @imgs.each{|i| image_tag i.floorplanphoto.thumb.url}  ) %>
                        ");

my partial js file is called, but somehow i got this error

NoMethodError in Units#getfloorplans

Showing C:/Users/lenovo/Documents/urbanace/urbanacecode/app/views/units/getfloorplans.js.erb where line #5 raised:
undefined method `gsub' for #<Array:0x164792b8>

Rails.root: C:/Users/lenovo/Documents/urbanace/urbanacecode

Application Trace
app/views/units/getfloorplans.js.erb:5:in `_app_views_units_getfloorplans_js_erb__484712465_186925308'

Framework Trace
actionview (4.2.7) lib/action_view/helpers/javascript_helper.rb:27:in `escape_javascript'
actionview (4.2.7) lib/action_view/template.rb:145:in `block in render'
activesupport (4.2.7) lib/active_support/notifications.rb:166:in `instrument'
actionview (4.2.7) lib/action_view/template.rb:333:in `instrument'
actionview (4.2.7) lib/action_view/template.rb:143:in `render'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
actionview (4.2.7) lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (4.2.7) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `instrument'
actionview (4.2.7) lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:52:in `render_template'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:14:in `render'
actionview (4.2.7) lib/action_view/renderer/renderer.rb:46:in `render_template'
actionview (4.2.7) lib/action_view/renderer/renderer.rb:27:in `render'
actionview (4.2.7) lib/action_view/rendering.rb:100:in `_render_template'
actionpack (4.2.7) lib/action_controller/metal/streaming.rb:217:in `_render_template'
actionview (4.2.7) lib/action_view/rendering.rb:83:in `render_to_body'
actionpack (4.2.7) lib/action_controller/metal/rendering.rb:32:in `render_to_body'
actionpack (4.2.7) lib/action_controller/metal/renderers.rb:37:in `render_to_body'
actionpack (4.2.7) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (4.2.7) lib/action_controller/metal/rendering.rb:16:in `render'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
activesupport (4.2.7) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
activesupport (4.2.7) lib/active_support/core_ext/benchmark.rb:12:in `ms'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
activerecord (4.2.7) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:43:in `render'
remotipart (1.2.1) lib/remotipart/render_overrides.rb:14:in `render_with_remotipart'
actionpack (4.2.7) lib/action_controller/metal/implicit_render.rb:10:in `default_render'
actionpack (4.2.7) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
actionpack (4.2.7) lib/abstract_controller/base.rb:198:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.2.7) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.2.7) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
activesupport (4.2.7) lib/active_support/callbacks.rb:505:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:505:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:92:in `__run_callbacks__'
activesupport (4.2.7) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'
activesupport (4.2.7) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.7) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (4.2.7) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `instrument'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
activerecord (4.2.7) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (4.2.7) lib/abstract_controller/base.rb:137:in `process'
actionview (4.2.7) lib/action_view/rendering.rb:30:in `process'
actionpack (4.2.7) lib/action_controller/metal.rb:196:in `dispatch'
actionpack (4.2.7) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
actionpack (4.2.7) lib/action_controller/metal.rb:237:in `block in action'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:74:in `call'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:43:in `serve'
actionpack (4.2.7) lib/action_dispatch/journey/router.rb:43:in `block in serve'
actionpack (4.2.7) lib/action_dispatch/journey/router.rb:30:in `each'
actionpack (4.2.7) lib/action_dispatch/journey/router.rb:30:in `serve'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:817:in `call'
rack (1.6.4) lib/rack/etag.rb:24:in `call'
rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'
rack (1.6.4) lib/rack/head.rb:13:in `call'
remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/flash.rb:260:in `call'
rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/cookies.rb:560:in `call'
activerecord (4.2.7) lib/active_record/query_cache.rb:36:in `call'
activerecord (4.2.7) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
activerecord (4.2.7) lib/active_record/migration.rb:377:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (4.2.7) lib/active_support/callbacks.rb:88:in `__run_callbacks__'
activesupport (4.2.7) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'
activesupport (4.2.7) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.7) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/reloader.rb:73:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'
web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'
web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.2.7) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.2.7) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.2.7) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.2.7) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.2.7) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.2.7) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
rack (1.6.4) lib/rack/runtime.rb:18:in `call'
activesupport (4.2.7) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/static.rb:120:in `call'
rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
railties (4.2.7) lib/rails/engine.rb:518:in `call'
railties (4.2.7) lib/rails/application.rb:165:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
rack (1.6.4) lib/rack/content_length.rb:15:in `call'
rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

Full Trace
actionview (4.2.7) lib/action_view/helpers/javascript_helper.rb:27:in `escape_javascript'
app/views/units/getfloorplans.js.erb:5:in `_app_views_units_getfloorplans_js_erb__484712465_186925308'
actionview (4.2.7) lib/action_view/template.rb:145:in `block in render'
activesupport (4.2.7) lib/active_support/notifications.rb:166:in `instrument'
actionview (4.2.7) lib/action_view/template.rb:333:in `instrument'
actionview (4.2.7) lib/action_view/template.rb:143:in `render'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
actionview (4.2.7) lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (4.2.7) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `instrument'
actionview (4.2.7) lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:52:in `render_template'
actionview (4.2.7) lib/action_view/renderer/template_renderer.rb:14:in `render'
actionview (4.2.7) lib/action_view/renderer/renderer.rb:46:in `render_template'
actionview (4.2.7) lib/action_view/renderer/renderer.rb:27:in `render'
actionview (4.2.7) lib/action_view/rendering.rb:100:in `_render_template'
actionpack (4.2.7) lib/action_controller/metal/streaming.rb:217:in `_render_template'
actionview (4.2.7) lib/action_view/rendering.rb:83:in `render_to_body'
actionpack (4.2.7) lib/action_controller/metal/rendering.rb:32:in `render_to_body'
actionpack (4.2.7) lib/action_controller/metal/renderers.rb:37:in `render_to_body'
actionpack (4.2.7) lib/abstract_controller/rendering.rb:25:in `render'
actionpack (4.2.7) lib/action_controller/metal/rendering.rb:16:in `render'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
activesupport (4.2.7) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
activesupport (4.2.7) lib/active_support/core_ext/benchmark.rb:12:in `ms'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
activerecord (4.2.7) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:43:in `render'
remotipart (1.2.1) lib/remotipart/render_overrides.rb:14:in `render_with_remotipart'
actionpack (4.2.7) lib/action_controller/metal/implicit_render.rb:10:in `default_render'
actionpack (4.2.7) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
actionpack (4.2.7) lib/abstract_controller/base.rb:198:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.2.7) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (4.2.7) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:117:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
activesupport (4.2.7) lib/active_support/callbacks.rb:505:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:505:in `call'
activesupport (4.2.7) lib/active_support/callbacks.rb:92:in `__run_callbacks__'
activesupport (4.2.7) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'
activesupport (4.2.7) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.7) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (4.2.7) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (4.2.7) lib/active_support/notifications.rb:164:in `instrument'
actionpack (4.2.7) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (4.2.7) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
activerecord (4.2.7) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (4.2.7) lib/abstract_controller/base.rb:137:in `process'
actionview (4.2.7) lib/action_view/rendering.rb:30:in `process'
actionpack (4.2.7) lib/action_controller/metal.rb:196:in `dispatch'
actionpack (4.2.7) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
actionpack (4.2.7) lib/action_controller/metal.rb:237:in `block in action'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:74:in `call'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:43:in `serve'
actionpack (4.2.7) lib/action_dispatch/journey/router.rb:43:in `block in serve'
actionpack (4.2.7) lib/action_dispatch/journey/router.rb:30:in `each'
actionpack (4.2.7) lib/action_dispatch/journey/router.rb:30:in `serve'
actionpack (4.2.7) lib/action_dispatch/routing/route_set.rb:817:in `call'
rack (1.6.4) lib/rack/etag.rb:24:in `call'
rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'
rack (1.6.4) lib/rack/head.rb:13:in `call'
remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/flash.rb:260:in `call'
rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/cookies.rb:560:in `call'
activerecord (4.2.7) lib/active_record/query_cache.rb:36:in `call'
activerecord (4.2.7) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
activerecord (4.2.7) lib/active_record/migration.rb:377:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (4.2.7) lib/active_support/callbacks.rb:88:in `__run_callbacks__'
activesupport (4.2.7) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'
activesupport (4.2.7) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.7) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/reloader.rb:73:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'
web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'
web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.2.7) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.2.7) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.2.7) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.2.7) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.2.7) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.2.7) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
rack (1.6.4) lib/rack/runtime.rb:18:in `call'
activesupport (4.2.7) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
actionpack (4.2.7) lib/action_dispatch/middleware/static.rb:120:in `call'
rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
railties (4.2.7) lib/rails/engine.rb:518:in `call'
railties (4.2.7) lib/rails/application.rb:165:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
rack (1.6.4) lib/rack/content_length.rb:15:in `call'
rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'



Request parameters
{"apt_id"=>"122",
 "_"=>"1472555205634"}

Session dump
_csrf_token: "***"
session_id: "*****"

Env dump
GATEWAY_INTERFACE: "CGI/1.1"
HTTP_ACCEPT: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01"
HTTP_ACCEPT_ENCODING: "gzip, deflate, sdch"
HTTP_ACCEPT_LANGUAGE: "en-US,en;q=0.8"
REMOTE_ADDR: "127.0.0.1"
REMOTE_HOST: "127.0.0.1"
SERVER_NAME: "localhost"
SERVER_PROTOCOL: "HTTP/1.1"

Response headers
None

i really have no idea what goes wrong, need some help to get this to work.

oh btw, i am really open if you have a better solution, kindly provide an example. many thanks

Rails 3 Secure Cookie and HTTP only

In my rails app, I am using a cookie called user_session user can access my rails app using https or http they can configure it.

Problem user_session cookie is set to http only but I want to make it as secure too.

If user access my app using http then the cookie will be in http only if he is using https then it will be set as secure cookie. I don't want to use 2 different cookies.

Configuration:

SampleApp::Application.config.session_store :cookie_store, key: '_user_session'

If I force :secure => true then this cookie is not available for the users who are all accessing in http request.

If any other details required please comment it out.

can't use daemons gem if installed with bundle install

I have these to .rb files inside a rails project:

require 'daemons'

Daemons.run('mqtt_subscriber.rb')


class MQTTSubscriber
  require 'mqtt'

  def run
    MQTT::Client.connect(:host => 'localhost', :port => 1883,) do |c|
      c.get('#') do |topic,message|
        puts "#{topic}: #{message}"
      end
    end
  end
end

mqtt = MQTTSubscriber.new
mqtt.run

If I run the command ruby mqtt_control.rb run it works properly when the daemons gem is installed with gem install daemons. But If the gem is installed with bundler, I get the following error:

/home/someuser/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- daemons (LoadError)
    from /home/someuser/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from mqtt_control.rb:1:in `<main>'

So it can't find the gem if it's installed though bundler. Probably because it doesn't install it in the default location.

How can I use gems installed with bundler in this way?

unable to install or reinstall/remove Ruby,Rails on OS X EI Capitan

$ gem update

Updating installed gems ERROR: While executing gem ... (Gem::RemoteFetcher::FetchError) bad response Not Found 404 (http://ift.tt/Td9dpv)

$ gem install rails

ERROR: Error installing rails: activesupport requires Ruby version >= 2.2.2.

$ gem install bundler

ERROR: While executing gem ... (Errno::EACCES) Permission denied - /Library/Ruby/Gems/2.0.0/gems/bundler-1.12.5/.codeclimate.yml

$ gem install rails -v 4.2.6

Fetching: activesupport-4.2.6.gem (100%) Successfully installed activesupport-4.2.6 ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /usr/bin directory.

Please help me , Thanks

Failed to build native extension

I switched to Linux Mint About a Two weeks ago and want to install my bundle for my website but my terminal is giving me error Resolving dependencies............. Using rake 11.2.2 Using i18n 0.7.0 Using json 1.8.3 Using minitest 5.9.0 Using thread_safe 0.3.5 Using builder 3.2.2 Using erubis 2.7.0 Using mini_portile2 2.1.0 Using pkg-config 1.1.7 Using rack 1.6.4 Using mime-types-data 3.2016.0521 Using arel 6.0.3 Installing debug_inspector 0.0.2 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2/ext    /debug_inspector
/usr/bin/ruby2.3 -r ./siteconf20160830-6661-3kryhn.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2/ext/debug_inspector
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2/ext/debug_inspector
make "DESTDIR="
compiling debug_inspector.c
In file included from /usr/include/ruby-2.3.0/ruby/ruby.h:36:0,
             from debug_inspector.c:12:
/usr/include/ruby-2.3.0/ruby/defines.h:26:19: fatal error: stdio.h: No     such file or directory
compilation terminated.
Makefile:239: recipe for target 'debug_inspector.o' failed
make: *** [debug_inspector.o] Error 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0   /gems/debug_inspector-0.0.2 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/debug_inspector-0.0.2/gem_make.out
Using bundler 1.11.2
Installing byebug 9.0.5 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/byebug-9.0.5/ext/byebug

/usr/bin/ruby2.3 -r ./siteconf20160830-6661-18ytmbw.rb extconf.rb creating Makefile

current directory: /var/lib/gems/2.3.0/gems/byebug-9.0.5/ext/byebug
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/byebug-9.0.5/ext/byebug
make "DESTDIR="
compiling breakpoint.c
In file included from /usr/include/ruby-2.3.0/ruby/ruby.h:36:0,
             from /usr/include/ruby-2.3.0/ruby.h:33,
             from byebug.h:4,
             from breakpoint.c:1:
/usr/include/ruby-2.3.0/ruby/defines.h:26:19: fatal error: stdio.h: No   such file or directory
compilation terminated.
Makefile:239: recipe for target 'breakpoint.o' failed
make: *** [breakpoint.o] Error 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/byebug-9.0.5 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/byebug-9.0.5/gem_make.out
Using coffee-script-source 1.10.0
Using execjs 2.7.0
Using thor 0.19.1
Using concurrent-ruby 1.0.2
Using multi_json 1.12.1
Using sass 3.4.22
Using tilt 2.0.5
Using spring 1.7.2
Installing sqlite3 1.3.11 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/sqlite3-1.3.11/ext/sqlite3

/usr/bin/ruby2.3 -r ./siteconf20160830-6661-3zztze.rb extconf.rb checking for sqlite3.h... * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
--with-sqlite3-dir
--without-sqlite3-dir
--with-sqlite3-include
--without-sqlite3-include=${sqlite3-dir}/include
--with-sqlite3-lib
--without-sqlite3-lib=${sqlite3-dir}/lib
/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
from /usr/lib/ruby/2.3.0/mkmf.rb:587:in `try_cpp'
from /usr/lib/ruby/2.3.0/mkmf.rb:1144:in `block in find_header'
from /usr/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for'
from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone'
from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone'
from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'
from /usr/lib/ruby/2.3.0/mkmf.rb:346:in `postpone'
from /usr/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for'
from /usr/lib/ruby/2.3.0/mkmf.rb:1143:in `find_header'
from extconf.rb:30:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/sqlite3-1.3.11/mkmf.log extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/sqlite3-1.3.11 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/sqlite3-1.3.11/gem_make.out
Using turbolinks-source 5.0.0
Using rdoc 4.2.2
Using tzinfo 1.2.2
Installing nokogiri 1.6.8 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/nokogiri-1.6.8/ext/nokogiri

/usr/bin/ruby2.3 -r ./siteconf20160830-6661-657qsw.rb extconf.rb Using pkg-config version 1.1.7 checking if the C compiler accepts ... * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/bin/$(RUBY_BASE_NAME)2.3
--help
--clean
/usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to    generate an executable file. (RuntimeError)
You have to install development tools first.
from /usr/lib/ruby/2.3.0/mkmf.rb:571:in `block in try_compile'
from /usr/lib/ruby/2.3.0/mkmf.rb:522:in `with_werror'
from /usr/lib/ruby/2.3.0/mkmf.rb:571:in `try_compile'
from extconf.rb:138:in `nokogiri_try_compile'
from extconf.rb:162:in `block in add_cflags'
from /usr/lib/ruby/2.3.0/mkmf.rb:629:in `with_cflags'
from extconf.rb:161:in `add_cflags'
from extconf.rb:414:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

/var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.6.8/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/nokogiri-1.6.8 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/nokogiri-1.6.8/gem_make.out
Using rack-test 0.6.3
Using mime-types 3.1
An error occurred while installing debug_inspector (0.0.2), and Bundler cannot
continue.
Make sure that `gem install debug_inspector -v '0.0.2'` succeeds before
bundling.

I tried to install the debug_inspector like this gem install debug_inspector -v 0.0.2 result: Building native extensions. This could take a while... ERROR: Error installing debug_inspector: ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2/ext/     \debug_inspector
/usr/bin/ruby2.3 -r ./siteconf20160830-6775-1iui5kl.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2/ext  /debug_inspector
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2/ext/debug_inspector
make "DESTDIR="
compiling debug_inspector.c
In file included from /usr/include/ruby-2.3.0/ruby/ruby.h:36:0,
             from debug_inspector.c:12:
/usr/include/ruby-2.3.0/ruby/defines.h:26:19: fatal error: stdio.h: No such   file or directory
compilation terminated.
Makefile:239: recipe for target 'debug_inspector.o' failed
make: *** [debug_inspector.o] Error 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/debug_inspector-0.0.2 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/debug_inspector-0.0.2/gem_make.out

update hash value with another hash

I wish my hash @fulfilments_to_send_notifications looked like:

{
  some_status: values: {
                     order_fulfillments: #some orders,
                     role: 'role',
                     minutes_between: 15 #some int
  }
}

I'm trying to update the values, currently it's just order fulfillments, but my code doesn't update it. I don't have the role or the minutes_between in my hash. How do I update it?

  def collect_fulfillments(late_fulfillments, role, status, minutes_between)
    @fulfilments_to_send_notifications[status] = {
      order_fulfillments: late_fulfillments,
      role: role,
      minutes_between: minutes_between
    }
  end

  def current_fulfillments
    @fulfilments_to_send_notifications ||= {}
    return unless current_fulfillments ||= begin
      OrderFulfillment.includes(:timestamps).new_fulfillments(10.days.ago)
    end # <---------- it works, returns some orders

    current_fulfillments.group_by(&:shopper_status).select do 
      |status, order_fulfillments|

      if status == 'shopper_started'
        if late_fulfillments =
          order_fulfillments.select do |order_fulfillment|
            order_fulfillment.pending_shopper_checkout?
          end
          collect_fulfillments( # <----- doesn't update the values
            late_fulfillments,
            :shopper,
            status,
            TIME_BETWEEN_NOTIFICATIONS_IN_MINUTES
          )
        end
      end
    @fulfilments_to_send_notifications
  end
end

When I joined multiple tables in ruby on rails I got Error : "uninitialized constant OfferLetter::Users"

I am new in ruby on rails,I want to joined multiple tables and extract data and print.I am posting my code...

this is my hr_controller.rb

@employees = OfferLetter.joins(:users, :user_details, :clients)

these are models "user.rb"

class User < ActiveRecord::Base has_many :offer_letter  end

"offer_letter.rb"

class OfferLetter < ActiveRecord::Base  belongs_to :users end

"client,rb"

class Client < ActiveRecord::Base belongs_to :user end

"user_details.rb"

class UserDetail < ActiveRecord::Base belongs_to :user end

here

  • "users table (id, email, first_name, last_name)"
  • "user_details table (user_id, contact_number, gender)"
  • "clients table (user_id,company_name)"
  • "offer_letters(candidate_id,client_id,created_by_id,ctc,cliend_address)"
  • here (id = user_id) in user and user_details and clients
  • (user_id = client_id) in clients and offer_letter
  • (candidate_id = id, created_by_id = id) in users and offerletter tables.
  • **I want to print first_name, last_name, contact_number, gender, ctc, cliend_address, compnay_name etc **

lundi 29 août 2016

Best place to check for env variables in Rails

I use ENV variables for all environments to set up different components of the stack, i.e. Redis, Memcached, etc.

I load all of these in the config/application.rb file, and before that I ensure that all environment variables are present.

I'm running into a problem now where I run a rake task before these variables are set, and so it fails my test. Rake seems to doing it's share correctly. This leads me to believe all of these variables initializations are in the wrong spot.

Now I'm at a loss as to the best place to instantiate all these services or check for their existence.

I am trying to open .rb file but I get an error message "in '

I'm completely new to this and I am following a course to learn coding but I can't seem to open the .rb files I downloaded with the course to follow along. In the video he double clicks the .rb file and command prompt opens with the code but when I double click the file my command prompt opens then immediately closes so I'm trying to open it manually by navigating to the directory where the program is located in command prompt. In ruby I type "cd Desktop" since the .rb file is on my desktop then I type "ruby 02_02integers.rb" which is the name of the file (I press tab after typing "02" since it fills the rest automatically") but when I press enter I get the error message above. This is the code in the .rb file I'm trying to open in command prompt, he's basically just showing different examples of integers.

# This file is a transcript of the IRB session shown in the movie.
# You should be able to cut and paste it into IRB to get 
# the same results shown in the comments.

# irb
1 + 1
# => 2
x = 2
# => 2
4 / 2
# => 2
4 * 2
# => 8
4 - 2
# => 2
4 ** 2
# => 16
x = 4
# => 4
x += 2
# => 6
x
# => 6
x = x + 2
# => 8
(1 + 2) * 3
# => 9
1234.class
# => Fixnum
123456789123456789.class
# => Bignum
x = 1234 * 1234 * 1234
# => 1879080904
x.class
# => Bignum
-200
# => -200
-200.abs
# => 200
200.next
# => 201
quit

Activrecord timestamp wrong assignment

for the following:

         updated_at         |         created_at         |   id    
----------------------------+----------------------------+---------
 2016-08-26 12:33:35.900201 | 2016-08-25 12:33:13.782502 | 2951380
 2016-08-26 12:33:35.916025 | 2016-08-25 12:33:13.781838 | 2951379
 2016-08-25 12:33:13.684854 | 2016-08-25 12:33:13.684854 | 2951377
 2016-08-25 12:33:13.684753 | 2016-08-25 12:33:13.684753 | 2951378
 2016-08-25 12:33:13.652293 | 2016-08-25 12:33:13.652293 | 2951376
 2016-08-26 12:32:59.669535 | 2016-08-25 12:33:13.589147 | 2951375
 2016-08-26 12:32:59.680676 | 2016-08-25 12:33:13.556841 | 2951374
 2016-08-26 12:32:59.559429 | 2016-08-25 12:33:13.496964 | 2951373
 2016-08-26 12:32:59.573863 | 2016-08-25 12:33:13.461594 | 2951372
 2016-08-26 12:31:10.338129 | 2016-08-25 12:33:13.400724 | 2951371

ID 2951378 has an earlier created_at (and updated_at) than the 2951377 record!

Anyone have any idea how that may happen, this records inserted by Queue worker handler.

Rails/Sqlite 3 - Displaying table data on page

I'm very very very new to Rails, and I've got a fast approaching deadline to code my first rail app as part of a challenge.

I've so far created the basic blog application, to get my head around how rails works.

I need to display a list of all data held within a table on a page in my site. In blog, I've got an index page - which lists all blog posts so I've been trying to follow the same process.

I've created a populated table in my database, and a controller - but when I try and display info from that database on my page I get the following error:

uninitialized constant RecordsController::Aliens

class RecordsController < ApplicationController
    def index
        **@records= Records.all**
    end
end

All I want to achieve is a simple table, which has the list of my records in, so far I'm not having much look recalling the data from the database.

Any help appreciated!

Rails and MQTT: Subscribe to topic in background at server startup?

I want to subscribe to a mqtt topic in my rails app when the server starts and and keep the subscription always active and running.

I'm using this mqtt gem for mqtt communication: http://ift.tt/1ABvDRN

Here is what I have right now:

in application.rb:

config.after_initialize do
 mqttSub = BackgroundMQTT.new
 mqttSub.run
end

BackgroundMQTT class:

class MQTTSubscriber
  def run
    Thread.new do
      MQTT::Client.connect(:host => 'localhost', :port => 1883,) do |c|
        c.get('#') do |topic,message|
          puts "#{topic}: #{message}"
          #Do things, access activerecord etc.
        end
      end
    end
  end
end

So basically the mqtt subscription starts in the after_initialize method and as far as I know, doesn't stop automatically?

Also As you can see, I'm running the subscription in a Thread, otherwise my rails application would stop doing anything else than listening to the mqtt subscription.

This seems to work at least for the first couple of minutes.

I'm not sure if this is a recommended way of doing what I want to do. Could this cause any issues that I haven't considered? What would be a recommend way of doing this?

Couldn't forward the HTTP response back to the HTTP client: It seems the user clicked on the 'Stop' button in his browser

I am facing a issue in which the request / response flow is not completing and i see a error message in passenger.log file as below and user is not clicking any close button.

Couldn't forward the HTTP response back to the HTTP client: It seems the user clicked on the 'Stop' button in his browser

The request is a large batch of processing employee records. I tried to modify the passenger_max_request_time but that did not work.

Can anyone please let me know what can i do so that the request continues without abruptly ending. Thanks.

Ruby on Rails - AbstractController::DoubleRenderError

i try to add to my create-method one redirect to my support tickets. But always i get an

AbstractController::DoubleRenderError

But i need this redirect after the upload of the file. How can i fix this ?

Upload-controller :

def create

   @upload = Upload.new(params[:upload])

      respond_to do |format|
          if @upload.save
           format.html {
             render :json => [@upload.to_jq_upload].to_json,
             :content_type => 'text/html',
             :layout => false
           }

           format.json { render json: {files: [@upload.to_jq_upload]}, status: :created, location: @upload }

        else
           format.html { render action: "new" }
           format.json { render json: @upload.errors, status: :unprocessable_entity }
        end
        redirect_to new_support_ticket_path
     end
end

upload.rb :

class Upload < ActiveRecord::Base
  attr_accessible :upload
  has_attached_file :upload

  include Rails.application.routes.url_helpers

  def to_jq_upload
    {
      "name" => read_attribute(:upload_file_name),
      "size" => read_attribute(:upload_file_size),
      "url" => upload.url(:original),
      "delete_url" => upload_path(self),
      "delete_type" => "DELETE" 
    }

  end

end

dimanche 28 août 2016

How to get all 'specific days' within a date range

How can I get let's say All the dates for Saturday and Sunday from X year to Y year and store them as array?

pseudo code would be

(year_today..next_year).get_all_dates_for_saturday_and_sunday

Or perhaps there are gems that cater to this already?

use memoization in my code

Been told to use memoization in my code not to call the function over and over. Is my implementation best way to use it? It seems redundant. Please advise how could I get rid of the initialize function.

class OrderService
  def initialize
    @current_orders = current_orders
  end

  def orders_acceptance
    @current_orders.
      with_statuses(:acceptance).
      select do |order|
        order.acceptance? if order.shopper_notified_at?
      end
  end

  def orders_start
    @current_orders.
      with_statuses(:start).
      select do |order|
        order.start?
      end
  end


  private

  def current_orders
    @current_orders ||= begin
      Order.includes(:timestamps).
        with_statuses(
          [
            :acceptance,
            :start
          ]
        )
    end
  end
end

Use joined table's data

I'm trying to access my joined table data but alas..

For example association between authors and books, author have many books: I'm using join funtion to join the author table to the books table in order to access the author's author_name attribute

class Author < ActiveRecord::Base
  has_many :books

  attr_accessible :author_name
end

class Book < ActiveRecord::Base
  belongs_to :author
end

random_author = Author.first
books = random_author.books.where(id > 5).joins(:author) #this should make all author attributes available to each book, right?

book_1 = books.first
book_1.author_name
=> NoMethodError: undefined method `author_name' for #<Book:0x111111>

Of course using the association would work: book_1.author.author_name but that will require another query, which is what I'm trying to avoid.

I mean the joins operation joins the author's data- there must be a way to access it right?

p.s. I can use includes method. and eager load the author data as well, but since I'm just needing a single attribute- is there a way to accomplished it with only a joins method? Thank you

.feature file of cucumber is not opening in ruby command prompt? need suggestion

.feature file of cucumber is not opening in ruby command prompt > I have install all gems, cucumber, watir, gherkin. I have created one text file and from IDE and saved it in feature folder as a .feature. when I am running on ruby command prompt with path its not opening. enter image description here

samedi 27 août 2016

what are the difference in ruby methods

What are the difference of the following method and how do it function/works?

method(x)

def method(x)
  # some codes
end  

method=(x)

def method=(x)
  # some codes
end

==(x)

def ==(x)
  # some codes
end

I kwow how method(x) works, it is a method with a required parameter. But I don't know how other methods works and when and how to use. Also I don't know the difference. Can someone explain it for me?

Thanks!

how to create a login page for only admin users in rails

How to create a separate signin page only for admin users, so the admin users only can login., please help me. Thanks.

Ruby/Rails. Passing variable into parameters

I have a lot pages in my app. And for every page I need to create a new variable and describe method. And if I will need to change something, I will have to change on every page. So the idea is to create universal method in application_controller.rb.

For example, I have a lot of categories in my Posts and to target some category for page I did: @posts_for_interesting = Post.where(interesting: true), other category, for example: @posts_for_photos = Post.where(photos: true).

And the application_controller.rb, have to look something like that:

def posts_for_all_pages(category)
  @posts = Posts.where(category: true)
end

And, for example, photos_controller.rb must look like that:

posts_for_all_pages(photos)

And how can I pass this photos to Post.where(category: true)?

vendredi 26 août 2016

Create multiple records with a simple form on Rails

I'm creating an inventory app, and one of the features is to change the stock inventory in bulk, so when you go to the Stocks link, it will show you a full list of items with 2 fields, INs and OUTs, once the user completes this and saves, it will be stored in the stock table (which has IN OUT and item_id fields, and created_at and updated_at)

So far i have been struggling with this, since all the examples i have been looking focus more on the item itself and not on the stock part (on my case)

Here is what i have so far:

this is the _form.erb on the stocks folder

<% @items.each do |item| %>
 <%= form_for item do |f| %>
  <%= f.fields_for :stocks, [Stock.new] do |stock| %>
   <%= f.label item.nombre %>
   Altas <%= stock.text_field :altas %>
   Bajas <%= stock.text_field :bajas %>
   <%= stock.hidden_field :items_id, :value => item.id %>
   <% end %>
  <%= f.submit %>
 <% end %>
<% end %>

I didnt do anything other than the scaffold on the controllers

and the models has this: stock.rb

class Stock < ActiveRecord::Base
 belongs_to :items
end

item.rb

class Item < ActiveRecord::Base
 has_many :stocks
 attr_accessible :nombre, :espesor, :material, :quantity
 accepts_nested_attributes_for :stocks
 attr_accessible :stocks_attributes
 self.per_page = 50

 protected
end

So far running this code, will show me each item name with both fields but also an update button for each item, and running the code will give me an error in the controller

unknown attribute 'item_id' for Stock.

and the following param is what im getting:

{"utf8"=>"✓",
"_method"=>"patch",
   "authenticity_token"=>"xAdfWBvf4MdkeiZ8xR5ElkNaMMTB5ySt1C9nCG5iGw2hwgDs1MJ2luLH2slvaEEIQBgjac4+RkxZIg6InIbZ1A==",
"item"=>{"stocks_attributes"=>{"0"=>{"altas"=>"7",
"bajas"=>"8",
"items_id"=>"4"}}},
"commit"=>"Update item",
"id"=>"4"}

so its only storing one value and not all 4 (on this case are 4 items)

Alert nil? method Ruby on Rails

I want to show a simple alert of the boolean value of the method nil in ruby rails within javascript. I am trying with the next sentence

alert("<% ''.nil? %>")

But I get a blank dialog box.

Could you help me?

In ruby on Rails what should the flow for execute rails application

I am new in Ruby on Rails, I have little bit confusion in Ruby on rails application. I have done all these things

routes.rb

Recruitment::Application.routes.draw do get 'hr/internal_employee_page', controller: 'hr', action: 'internal_employee_page'  get 'hr/permanent_consultant_page' => 'hr#permanent_consultant_page', as: :permanent_consultant_page end 

hr_controller.rb

class HrController < ApplicationController

def internal_employee_page
    @employees = OfferLetter.all
    # render :text => @employees.inspect        
end

def employee_details
    @employees = OfferLetter.all
end

end

_hr_page.html.erb

<%= render 'hr/dashboard'%> <%= render 'hr/internal_employee_page'%>

_internal_employee_page.html.erb

<div id="job_details">
    <%= render "hr/employee_details" %>
</div>

_employee_details.htmlerb

<% @employees.each do |emp| %>
    <h3> Employee Name : <%= emp.full_name %> </h3>
<% end %>

then i got error is : undefined method `each' for nil:NilClass When i did trace then i found hr_controller.rb is not execute, when i commented all hr_controller.rb then I got same error. So please tell me where am i wrong and what is problmes ...

Rails Search and add filters to the search - geocoder


I would like some advices on the way to add a filter , on my search form with geocoder.


I got a User model and Animal model (animals got a Type argument)
And a join table : Animal_User with Animal_ID / User_ID)

Right now, I can locate Users around a city with the choice of Kilometers around that city.That's working fine.

I would like to add the filter on the type of animal, that would be great :)

Search would look like this : London > 10KM > Filter on Type : dogs

Many thanks in advance if you have a glimpse of an idea on how to do that. You will find the search html and the controller. If you need User Model or Animal model i can post it too ( it's really standard Has_many / has_many though association)

search.html.erb

<div class="search-bar">
<%= form_tag search_path, :class => "webdesigntuts-workshop", method: :get do %>
  <%= label :user, "" %>
  <%= text_field_tag :city, params[:city], placeholder: 'City', :input_html => { :value => 'Paris' } %>

  <%= label :distance, "" %>
  <%= text_field_tag :distance, params[:distance], placeholder: 'km', :input_html => { :value => '10' } %>

  <%= submit_tag "Search" %>
<% end %>
</div>

search controller

class SearchsController < ApplicationController
    def search
    if params[:city].present?
      @searchs = User.near(params[:city], params[:distance] || 10).where("id != ?", current_user.id)
    else
      @searchs = User.all.where("id != ?", current_user.id)
    end
  end

end

Unable to install an old version of the gem "rmagick"

I happen to have a bit old rails project, it's rails 3.2 and ruby 2.2.4. Because of this, installing some gems fails, in particular it's "rmagick -v '2.13.2'".

    $ gem install rmagick -v '2.13.2'
    Building native extensions.  This could take a while...
    ERROR:  Error installing rmagick:
            ERROR: Failed to build gem native extension.

        /home/user123/.rubies/ruby-2.2.4/bin/ruby -r ./siteconf20160826-3014-1j0i394.rb extconf.rb
    checking for Ruby version >= 1.8.5... yes
    checking for gcc... yes
    checking for Magick-config... yes
    checking for ImageMagick version >= 6.4.9... yes
    checking for HDRI disabled version of ImageMagick... no

    Can't install RMagick 2.13.2.
    RMagick does not work when ImageMagick is configured for High Dynamic Range Images.
    Don't use the --enable-hdri option when configuring ImageMagick.

    *** extconf.rb failed ***
    Could not create Makefile due to some reason, probably lack of necessary
    libraries and/or headers.  Check the mkmf.log file for more details.  You may
    need configuration options.

    Provided configuration options:
            --with-opt-dir
            --without-opt-dir
            --with-opt-include
            --without-opt-include=${opt-dir}/include
            --with-opt-lib
            --without-opt-lib=${opt-dir}/lib
            --with-make-prog
            --without-make-prog
            --srcdir=.
            --curdir
            --ruby=/home/user123/.rubies/ruby-2.2.4/bin/$(RUBY_BASE_NAME)

    extconf failed, exit code 1

    Gem files will remain installed in /home/user123/.gem/ruby/2.2.4/gems/rmagick-2.13.2 for inspection.
    Results logged to /home/user123/.gem/ruby/2.2.4/extensions/x86_64-linux/2.2.0-static/rmagick-2.13.2/gem_make.out

I've tried unistalling the library "ImageMagick" and installing one with no hdri, but even that failed because there're other libraries which depend on "ImageMagick" with hdri, thus I haven't been able to reinstall it. And in general, reinstalling a library only for a single rails project doesn't sound a right thing to do.

What would you recommend me then? I'm on Arch Linux and have 2 rubies installed:

$ chruby
 * ruby-2.2.4
   ruby-2.3.1

Maybe I should upgrade it to a slitely newer version? Note that I don't want to break other dependencies in the project.

Invalid reset password token Error ! Devise 3.1

Few days back, I changed my app to authenticate users through either username or Email address. It works fine with registration and login.

but it throws an error Reset password token is invalid for forgot password after such change. it was working fine before.

I am using Devise 3.1 & Rails 3.2.13

Any help in this would be much appreciated.

UrlGenerationError Missing Required Key [:id] Error?

When i want to create an article. i get this error after clicking on the create article button "No route matches {:action=>"show", :controller=>"articles", :id=>nil} missing required keys: [:id]"

although i make sure there is a user who is logged in before creating the article. Here's my code:

articles_controller.rb

class ArticlesController < ApplicationController
before_action :require_user , except:[:index,:show]

def index
    @articles = Article.all
end

def new
    @article = Article.new
end

def create
    @article = Article.new(article_params)
    if @article.save
        flash[:notice] = "Your Article was Created"
    else
        render 'new'
    end
    redirect_to article_path(@article)
end

def show
    @article = Article.find(params[:id])
end

def edit
    @article = Article.find(params[:id])
end

def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
        flash[:notice] = "Your Article was Updated"
        redirect_to article_path(@article)
    else
        render 'edit'
    end

end

def destroy
    @article = Article.find(params[:id])
    @article.destroy
    flash[:notice] = "Your Article was deleted"
    redirect_to articles_path(@article)
end

private

def article_params
    params.require(:article).permit(:title,:description)
end

end

users_controller.rb

class UsersController < ApplicationController
def index
    @users = User.all
end

def new
    @user = User.new
end

def create
    @user = User.new(user_params)
    if @user.save
        flash[:success] = "You Signed up successfully"
        redirect_to articles_path
    else
        render 'new'
    end

end

def show
    @user = User.find(params[:id])
end

def edit
    @user = User.find(params[:id])
end

def update
    @user = User.find(params[:id])
    if @user.update(user_params)
        flash[:success]= "Your user was updated"
        redirect_to articles_path
    else
        render 'edit'
    end
end

private

def user_params
    params.require(:user).permit(:username,:email,:password)
end

end

views/new.html

    <h1>New Article</h1>
<%= form_for @article do |f| %>

<p>title<%= f.text_field :title %></p><br>
<p>description<%= f.text_area :description %></p>
<%= f.submit "Create" %>
<%end%>

here's my github repo

my github repo

To Do task that recurs every x interval

I'm currently building a to-do list (I know there are existing gems but I'm doing a tailored fit feature for a specific project).

One of the biggest issue I'm having is creating the feature like in Google calendar where you can create a to-do task that will show up every x days. I can easily calculate this on the current month since there's start date but the problem is when I proceed to the succeeding months (the user can move forward ahead so I can't save the last day from previous month) I lose track of when the dates should properly appear.

If anyone can point me to the right direction or give a basic formula for this I would gladly appreciate it.

Storage for Big Blue Button

I have the following doubts for storage in BBB recordings:

  1. Where is the recording being stored?

    • I saw that its stored in /var/bigbluebutton folder on the server where BBB is installed. But there are many folders there. Which is the exact folder I should look for?
  2. How much space is allotted for storage?

    • Is it the same space that I have for my server since my recordings are stored on the server itself?
  3. Other than the user deleting the recording, how long are recordings stored? Should we have a job that is scheduled to remove them? (We do not anticipate needing to save them in definitely, perhaps just for the semester.)

Can someone please help me?

jeudi 25 août 2016

undefined method `image' for #0x7d6a5a0>

I have this big problem, when I access the URL as localhost:3000/pics/new creat New post show this problème :

NoMethodError in Pics#new

Showing c:/Sites/insta/app/views/pics/_form.html.haml where line #12 raised:
undefined method `image' for #<Pic:0x7d6a5a0>
Trace of template inclusion: app/views/pics/new.html.haml
Rails.root: c:/Sites/insta

app/views/pics/_form.html.haml:12:in `block in _app_views_pics__form_html_haml___995842594_67564884'
app/views/pics/_form.html.haml:1:in `_app_views_pics__form_html_haml___995842594_67564884'
app/views/pics/new.html.haml:7:in `_app_views_pics_new_html_haml__952992882_75084336'

_form.html.haml

enter image description here

new.html.haml

enter image description here

ActionView::Template::Error (undefined method `full_name' for nil:NilClass )

I am adding new role in my role table, role is successfully added and it's working properly. In the view automatically hr folder created (I add two new page _internal_employee_page.html.erb, _employee_details.html.erb) I have created one controller hr_controller.rb

My _internal_employee_page.html.erb page

<div class="client-dash-page head-border matching-profile recrut-dashboard">
    <div id="job_details">
        <%= render "hr/employee_details" %>
    </div>
</div>

My _employee_details.html.erb page

<div class="panel-group" id="client-dash-accordion" role="tablist" aria-multiselectable="true">

Employee Name : <%= @employees.full_name %>


This is my Controller

class HrController < ApplicationController

def internal_employee_page
    @employees = OfferLetter.all        
end

def employee_details
    @employees = OfferLetter.all
end

end

I have two model ( UserHr.rb and OfferLetter.rb ) this is my UserHr.rb model

class UserHr < User
attr_accessor :full_name
has_many :offer_letter

end

My OfferLetter.rb model

class OfferLetter < ActiveRecord::Base
    belongs_to :user_hr
end

This is my routes.rb

Recruitment::Application.routes.draw do

get 'hr/internal_employee_page' => 'hr#internal_employee_page', as: :internal_employee_page end

The error is here

Employee Name : <%= @employees.full_name %>

full_name is column name, I want to print the value of full_name column. Please help me I have try so many times but i am not solve this problems.

Rails script terminating in between

I am trying to debug a rails script which is terminating in between, i am doing API calls and processing results in Batch format.

when my action is executed say its executed for 50 employees in a batch, for every employee i do a API call and process the response. But i observed that some times the script executes as expected but sometimes it terminates at different points, no specific pattern observed.

can anyone suggest as to what could be going wrong, how can u debug it further and reach the conclusion as to what could be going wrong.

Also i see that in the log the action is executed twice, i.e. the first time the script terminates abruptly it again makes an entry in the log not sure how that happens

for example i see http://ift.tt/2birYUL called twice in the log.

mercredi 24 août 2016

integrate only oauth2 in rails app without doorkeeper

I have been check and tested how doorkeeper works. I am new to oauth/oauth2, so I am puzzled if it can work alone without doorkeeper or grape. The question is can I create authentication using oauth/oauth2 alone? How can I possible do it. For example, I have a store app and I want to integrate oauth2 for my API, how can I possibly do it? Can anybody give me an idea or give some bunch of links of tutorials?

Thanks!

Nested form working in new but not showing up in edit Rails

I'm making a invoice application where i have the @invoice form and inside it i have nested forms for customers, products, and company information. The products form is working fine in all views but the customer form isn't. When i fill in the customer information and create a new invoice it works. But when i try to edit that invoice the entire form is gone.

invoice_form

<%= f.fields_for :customer do |customer| %>
                            <div class="field">
                              <%= customer.label 'Bedrijfsnaam ontvanger' %><br/>
                              <%= customer.text_field :company_name, placeholder: 'bedrijfsnaam', class: 'form-control' %>
                            </div>
                            <div class="field">
                              <%= customer.label 'Adres ontvanger' %><br>
                              <%= customer.text_field :address_line_1, placeholder: 'adres ontvanger', class: 'form-control' %>
                            </div>
                            <div class="field">
                              <%= customer.label 'Postcode & stad' %><br>
                              <%= customer.text_field :zip_code, placeholder: '1234AB Rotterdam', class: 'form-control' %>
                            </div>

Invoices_controller.rb

class InvoicesController < ApplicationController
  before_action :set_invoice, only: [:show, :edit, :update, :destroy]

  # GET /invoices
  # GET /invoices.json
  def index
    @invoices = Invoice.all
  end

  # GET /invoices/1
  # GET /invoices/1.json
  def show
  end

  # GET /invoices/new
  def new
    @invoice = Invoice.new
    @invoice.products.build
    @invoice.build_customer
  end

  # GET /invoices/1/edit
  def edit
  end

  # POST /invoices
  # POST /invoices.json
  def create
    @invoice = Invoice.new(invoice_params)

    respond_to do |format|
      if @invoice.save
        format.html { redirect_to @invoice, notice: 'Invoice was successfully created.' }
        format.json { render :show, status: :created, location: @invoice }
      else
        format.html { render :new }
        format.json { render json: @invoice.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /invoices/1
  # PATCH/PUT /invoices/1.json
  def update
    respond_to do |format|
      if @invoice.update(invoice_params)
        format.html { redirect_to @invoice, notice: 'Invoice was successfully updated.' }
        format.json { render :show, status: :ok, location: @invoice }
      else
        format.html { render :edit }
        format.json { render json: @invoice.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /invoices/1
  # DELETE /invoices/1.json
  def destroy
    @invoice.destroy
    respond_to do |format|
      format.html { redirect_to invoices_url, notice: 'Invoice was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_invoice
      @invoice = Invoice.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def invoice_params
      params.require(:invoice).permit(:number, :currency, :date, :duedate, :btwtotal,
                                      :subtotal, :total, :footer, customers_attributes: [:id, :company_name, :address_line_1, :zip_code, :_destroy],
                                      companies_attributes: [:id, :btw_number, :iban_number, :kvk_number, :company_name, :_destroy],
                                      products_attributes: [:id, :quantity, :description, :unitprice, :btw, :total])
    end
end

Invoice.rb - (model)

class Invoice < ActiveRecord::Base

  has_one :company
  has_one :customer
  has_many :products

  accepts_nested_attributes_for :customer, reject_if: :all_blank, allow_destroy: true
  accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true
  validates :number, :currency, :date, :duedate, :btwtotal, :subtotal, :total, presence: true

end

Includes association

How can I load this from fewer queries?

Current code; Controller;

@players = @season.players.includes(:stats)

Views;

<% @players.each do |player| %>
    <%= player.stats.where(season: @season).each do |stat| %>
    <% end %>
<% end %>

Thank you.

What is the difference between Ruby and Ruby on Rails (web framework)? [duplicate]

This question already has an answer here:

I would like to know more about the Ruby and Ruby on Rails.

How do you develop an application - what does an application structure look like utilising Ruby on Rails.

Where would you use Ruby?

Upgrading Rails 3.2 to Rails 5

I have a Rails 3.2 project that has 30 models and about 20 controllers. It's not a super huge codebase and its pretty much an idiomatic Rails site.

Is there any advantage to just doing rails new and controller by controller, model by model, gem by gem just copy and pasting things in and getting everything running on a fresh Rails 5 instance?

I just see some pain trying to do an upgrade version by version. Is this a viable way to upgrade a project where I have written all the code and know the project well?

mardi 23 août 2016

Rendering js.erb in rails

i want to try my js.erb if it is working?

here my view posts/index to trigger

 <%= link_to "Like", {:controller => 'post', :id => post , :action =>'like'}, class: "btn btn-danger btn-xs", remote: true %>

my post controller

def like
@user = current_user
@post.liked_by(@user)
redirect_to posts_path
respond_to do |format|
  format.html {redirect_to posts_path}
  format.js { render :action => 'stablelike' }

end
end

and this is my js.erb to test

alert("working");

and this is my error: when i inspect my Chrome

AbstractController::DoubleRenderError at /post/like/85

Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

app/controllers/posts_controller.rb, line 83

 ``` ruby
 78       @user = current_user
 79       @post.liked_by(@user)
 80       redirect_to posts_path
 81       respond_to do |format|
 82         format.html {redirect_to posts_path}

83 format.js { render :action => 'stablelike' } 84
85 end 86 end 87

Sending POST request from android to RoR app, but cannot find the right URL

I am not able to reach the create Method in tests_controller.rb with this code.

String newUrl = "http://ift.tt/2bseNRw";

        httpcon = (HttpURLConnection) ((new URL(newUrl).openConnection()));
        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Content-Type", "application/json");
        httpcon.setRequestProperty("Accept", "application/json");
        httpcon.setRequestMethod("POST");
        httpcon.connect();

And here is my routes.rb (I use model scaffold to create the RoR app).

resources :tests

Am i wrong in routing or something. When i run this code in Android, the create method is not run at all.

lundi 22 août 2016

How do I add a gem to my project and actually see the visual difference it makes?

I feel as if I am missing something very obvious here. I have searched for days on how to add gems to my ruby on rails project. So far, the furthest I have gotten is installing the gem and using bundle install, but how do I actually implement it into my website project? The specific gem I am looking at using is a Carousel image slider called Slick. It slides one by one to another image and allows the user to also click one of two buttons to go back or forward to another image. I downloaded the slick file and I clearly see that it has a good bit of coding in it. Am I supposed to drag that file into a specific folder in my rails project directory? Please Help!

How to set correct namespace in Rails models?

In app/models/sudoku, I have 6 classes.

  1. app/models/sudoku/sudoku.rb
  2. app/models/sudoku/board.rb
  3. app/models/sudoku/cell.rb
  4. app/models/sudoku/row.rb
  5. app/models/sudoku/column.rb
  6. app/models/sudoku/block.rb

class Sudoku < ActiveRecord::Basecalls class Board, and class Board calls class Cell, class Row, etc. Like this:

- sudoku.rb 
 - board.rb
   - cell.rb
   - column.rb
   - row.rb
   - block.rb

When I run the code on class Sudoku, I get a Unable to autoload constant Sudoku::Board error. I understand this completely, that when you add a new sub-dir into the models dir, you need to have the name space convention.

But, when I name app/models/sudoku to app/models/foo, I don't have to use ANY name space.

Why does this happen?

ruby on rails - can't add a new post

Processing by PostsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"DXrr78QugzRU4TQ+8StPOR79VE/Fd8DFKzBSJyd1LKFrb3hhcXAjOyTj1eVxb3Tz1QbLGHdXC3R5oboDFSTI1w==", "post"=>{"title"=>"Blog post", "body"=>"does this work?", "category_id"=>"1"}, "commit"=>"Add Post"} (0.0ms) BEGIN (1.0ms) ROLLBACK Rendering posts/new.html.erb within layouts/application

How to eager load related models when indexing using SearchKick / ElasticSearch?

This is my search_data method:

def search_data
  {
    email: email,
    skills: interests.pluck(:name)
  }
end

where my User has_many :skills. When I run User.where(conditions).reindex it load the skills records like

SELECT * FROM skills WHERE skills.user_id = 1
SELECT * FROM skills WHERE skills.user_id = 2
SELECT * FROM skills WHERE skills.user_id = 3
SELECT * FROM skills WHERE skills.user_id = 4
. . .

I wonder if it's possible to make it load like this:

SELECT * FROM skills WHERE skills.user_id IN (1, 2, 3, 4, . . .)

Model with huge number of fields

I have model Car and fields vin:uniq a_field1 a_field2 a_field3 .. a_field20 b_field1 b_field2 b_field3 .. b_field30. I have two kinds of users Mechanik and Manager. Mechanik can see and edit a_ parameters and manager is able to see and edit b_ parameters. Nobody can edit vin. Both of users can create Car with vin and a_ parameters for Mechanik and vin and b_ parameters for manager. Is it better to divide the model car and connect them by has_one and belongs_to or have one big model with all parameters. Maybe there is another better approach? How it should looks like?

dimanche 21 août 2016

When to use require vs ActiveSupport::Concern?

I wrote a sudoku solver program in Ruby that I want to place inside a Rails 4 app. The file structure for the program at the moment is as follows.

- sudoku_solver.rb 
 - board.rb
   - cell.rb
   - column.rb
   - row.rb
   - block.rb

Each hierarchy is linked together with require_relative.

Now in Rails, I've created model/sudoku.rb, which is intended to be sudoku_solver.rb. I've read about mixins, concerns, and I don't know how to choose the correct one to use over simply requiring model/sudoku/board.rb, model/sudoku/cell.rb, etc.

Any guidance would be appreciated. Here's the repo for the Ruby program is one wants to see it.

samedi 20 août 2016

Rails attr_accessible atrribute isn't working isn't working

I'm doing this tutorial in Rails + Devise and I've stuck my head. There's this:

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :name, :password, :password_confirmation, :remember_me 

    validates :email, :presence => true, :uniqueness =>

I tried to translate it to Rails5 since attr_accesible isn't working Rails5 but seriously...I'm in the corner. What's the proper way to do here to make it work? I tried to define a method with permit parameters but it didn't really work out. I'd be really glad if you could give me a good hint on that!

Ruby on Rails Simple Forms Error

I'm a Ruby and Ruby on Rails beginner, started 2 days ago. I'm trying to build a basic app for the first time and I get this error when I try to use simple_forms gem.

Before I show you the code I want to specify that if I delete the simple_forms code, it works, it redirects me to /orders/new page and it display the HTML page.

This is my error: NoMethodError in Orders#new Showing /home/ubuntu/workspace/app/views/orders/_form.html.erb where line #2 raised: undefined method `amazonurl' for #

My code:

routes.rb

Rails.application.routes.draw do

resources :orders

root 'orders#index'

end

orders_controller

class OrdersController < ApplicationController
    def index
    end

    def new
        @order = Order.new
    end

    def create
        @order = Order.new(order_params)
    end

    private
    def order_params
        params.require(:order).permit(:amazonurl, :dname, :daddress, :dphone)
    end
end

Migration

class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|

      t.string :amazonurl
      t.text :dname
      t.text :daddress
      t.text :dphone

      t.timestamps null: false
    end
  end
end

Form ( _form.html.erb)

<%= simple_form_for @order  do |f| %>
  <%= f.input :amazonurl %>
  <%= f.input :dname %>
  <%= f.input :daddress %>
  <%= f.input :dphone %>
  <%= f.button :submit %>
<% end %>

And my new.html.erb file

<h1>New Order</h1>
  <%= render 'form' %>

Thank you very much, I hope we figure it out!

What should i choose for the future (Ruby on Rails or Coldfusion)? [on hold]

I don't know with what tag should i ask this, but i have dilemma in my thoughts for now. I would like to hear the best possible way to decide. I am 22 years young, started to learn programming when i was around 19. The first language what i seriously took was Ruby on Rails, i was starting to learn it 2015 on July. I was hoping that i could get a Ruby on Rails job as fast as possible I really enjoyed it but it was hard to learn. So i stoped to learn Ruby on Rails on 2016 February because i knew one person through my father which thinked a lot and at the end offered me database developer role which they needed a lot. I told him that im not so good at databases but that was ok. I did not felt like junior Ruby on Rails developer btw. I was happy that i get first offer and i accepted it. The role was based in London. Company is based generally on ColdFusion and on SQL. I've started on March to learn SQL, but after two or three months i started to learn even other things that the company does about coldfusion and system administrating.

Is that ok that im receiving 20k £ / year as junior developer? Even now im working there 5 months and when should i ask for rise? Guys who are teaching me tells that im fast learner but with weak previous knowledge.

And the time has come that i started to think about future, about that i want to receive good salary, but CF is not the one instead of Ruby on Rails which is a lot more demanding language nowadays.

I think that it is good that i have started to work there. But i'm thinking what i could learn at home as extra - CF or ROR? If i will learn ROR then probably in future i will change my job to it. This is too complicated for to think out, maybe you can tell some advise or is my situation fine enough for now?

Thank you

Cocoon gem inside a table in rails

I'm busy with a invoicing application and i'm trying to put a nested form from the cocoon gem inside a <tbody></tbody>. The nested form is working perfectly but it doesn't show up in the <tbody></tbody> but at some random place above the table head. I think it's because you can't have <div class=nested-fields></div> inside the table body but i'm not sure how to do it differently.

enter image description here

i have this in my invoices/_form.html.erb :

    <div class="row">
      <div class="col-sm-12">
        <table class="table table-striped">
          <thead>
          <tr>
            <th class="hidden-480"> Hoeveelheid </th>
            <th class="hidden-480"> Beschrijving </th>
            <th class="hidden-480"> Bedrag </th>
            <th class="hidden-480"> Totaal </th>
            <th class="hidden-480"> Btw(%) </th>
          </tr>
          </thead>
          <tbody>
            <%= f.fields_for :products do |product| %>
            <%= render 'product_fields', f: product %>
            <%= link_to_add_association 'Item toevoegen', f, :products, class: 'btn btn-primary btn-success' %>
            <% end %>
          </tbody>
        </table>
      </div>
    </div>

invoices/_product_fields.html.erb

<div class="nested-fields">
    <tr>
      <td> <%= f.text_field :quantity %> </td>
      <td> <%= f.text_area :description %> </td>
      <td> <%= f.number_field :unitprice %> </td>
      <td> €200  </td>
      <td> <%= f.select(:btw, [[' 21%', 21, title: '21%'],[' 6%', 6, title: '6%'], [' 0%', 0, title: '0%']]) %> </td>
    </tr>
  <%= link_to_remove_association 'x', f, class: 'btn btn-primary btn-danger' %>
</div>

Any idea what's going on? Help would be much appreciated!

Toggle switch / T-Flip Flip

I am having trouble trying to apply a flip-flop to the following scenario. Say I have the following array:

[ 'on',
  'random text',
  'random text',
  'random text',
  'random text',
  'off'
  'random text',
  'random text',
  'on'
  'random text',
  'off'
  'random text',
  'random text',
   etc...

I want a switch to flip according to one of two values (as represented by 'on' and 'off' in the array)

How would I go about this in Ruby? I can see the flip-flop functionality, but unfortunately I have no way of determining a value to trigger true/true as the text will always be random.

Any help is appreciated

vendredi 19 août 2016

Change pseudo-absolute assets path in Rails 3

I tried every way I found, but I don't know how to do it.

Rails always write /assets/... and would like to have ./assets/ or assets/ because my application is in a subfolder, not in the root folder.

I tried with config.action_controller.asset_host = "." but Rails write http://./assets/

I tried with config.assets.prefix = "." but rails write /./assets/

Suppose that my application lives in: http://ift.tt/OXbkMi, with the default behaviour of Rails every path point to http://domain.com/ not to http://ift.tt/OXbkMi and I don't want to specify an absolute path, because that is not portable.

Check this as example: http://ift.tt/1q1jHH1

Event system in rails

I am an experienced PHP developer and i am used with the event system in Laravel. Is there something similar in Rails? I like this concept very much and I am amazed that Rails does not have something like this by default. Or at least it is not in the documentation.

jeudi 18 août 2016

How to recreate a ruby and rails database when using structure.sql

I want to create a database from an existing app. At some time in the past I squashed the migrations, so I cannot use db:create followed by db:migrate. So how do I do it?

cannot load such file -- bundler/setup (LoadError) (bad ruby version)

I'm trying to deploy a rails app on a VPS. I've already done that but this is the first time I get this error, and I can't find a way to solve it, even though I know what's wrong:

I used RVM to install ruby 2.3.1, and Apache to run the whole thing. I want to use Phusion Passenger to deploy this. So far, all I get is the following error:

cannot load such file -- bundler/setup (LoadError)
  /usr/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /usr/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:263:in `block in run_load_path_setup_code'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:366:in `running_bundler'
  /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:261:in `run_load_path_setup_code'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:100:in `preload_app'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:158:in `<module:App>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<module:PhusionPassenger>'
  /usr/share/passenger/helper-scripts/rack-preloader.rb:28:in `<main>'

I read that the problem could come from 2 issues: bundler is not installed, or the ruby version that passenger tries to use isn't correct. Here, passenger tries to use ruby 2.1.0 while I get ruby 2.3.1 when running ruby -v

My question is the following: how can I change which rails version Passenger has to use ?

P.S. : I used this tutorial to get so far, excepted that I installed RVM instead of compiling ruby components myself as described.

Thank you in advance

How to write xls to tmp folder

I followed the railscasts tutorial on how a render an excel file (http://ift.tt/MmX2RS). We already have a lot of code on it so I'm trying to avoid rewriting by using a gem. How can I make it write to the rails /temp directory instead of letting the user download it? After it gets generated, I'll just attach it to an email and send to the user instead of letting the user wait for a long time. My problem now is how to write to the temp directory.

def mymethod
  @products = Product.order(:name)

  respond_to do |format|
    format.xls
  end
end

We are using rails 3.2.

mercredi 17 août 2016

Rails Index Directory

I've recently setup a new Rails environment with MySQL but when I run the application the preview just shows up with the app directory. I've tried editing my database.yml file to work with MySQL but but can't get it to work.

These are my database.yml default settings:

default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: <%=ENV['darraghsan']%>
host: <%=ENV['IP']%>
password:
socket: /var/run/mysqld/mysqld.sock

I've added a screenshot of what I see when I run my app,

Any help is appreciated.

ruby merge variables to test for all present?

Is there a way to true up this operation and make it cleaner?

def testvars?
  var1.present? && var2.present? && var3.present?
end

There has to be a better way...

Ranking in ActiveAdmin

I have difficulty in one particular task in ActiveAdmin (I am a beginner in Rails). I have a Route model in which there is a start location, an arrival location, a distance, a duration etc... I want to configure ActiveAdmin so that i have a page that show the top 10 route depending on the start location and the arrival location (i.e : ‘London-> ‘Manchester' number 1 with 32 routes, ‘Swansea’ -> ‘Cardiff’ number 2 with 27 routes). I have looked for a way to do it but Nothing looked to fit my problem. I found Ransack for sorting and searching but I don’t think it is what I need. If you have any advices, tutorials or resources to help, it would help me a lot !

Sorry for my bad English and thanks in advance !

Converting belongs_to with includes from Rails 3 to Rails 4

I'm having trouble converting a belongs_to relationship with an includes from the Rails 3 format to Rails 4.

# Rails 3, this works fine.
class Mobileownerdisclosure < ActiveRecord::Base
  belongs_to :mobileuser, foreign_key: 'mobileowner_id', conditions: "mobileownerdisclosures.mobileowner_type = 'Mobileuser'", include: :mobileownerdisclosures
end

# Rails 4 format that I can not get to work...
class Mobileownerdisclosure < ActiveRecord::Base
  belongs_to :mobileuser, -> { where("mobileownerdisclosures.mobileowner_type = 'Mobileuser'").includes(:mobileownerdisclosures) }, foreign_key: 'mobileowner_id'
end

The .includes(:mobileownerdisclosures) just doesn't seem to be considered at all. However, if I change this from an includes to a joins, it works fine.

# Rails 4 format with joins instead of includes.
class Mobileownerdisclosure < ActiveRecord::Base
  belongs_to :mobileuser, -> { where("mobileownerdisclosures.mobileowner_type = 'Mobileuser'").joins(:mobileownerdisclosures) }, foreign_key: 'mobileowner_id'
end

But since I am converting a very large project from Rails 3 to Rails 4, I'd rather keep it includes like the original intent, just to be sure the original coder didn't need it this way.

Why is the includes not being considered? Is there a different way to use includes other than what I am doing there?

Thanks in advance.

xray-rails not working with rails 4

xray-rails Ctrl+Shift+X is not working with Rails 4

Gemfile

group :development, :test do
  gem 'xray-rails'
end

development.rb

config.assets.debug = true

I bundled it

.
.
Using sass-rails 5.0.4
Using turbolinks 2.5.3
Using xray-rails 0.1.21
Bundle complete! 17 Gemfile dependencies, 68 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.

Inspecting the element in browser with F12 shows me

<!--XRAY START 37 /home/sample/app/views/shared/_list.html.haml-->
<ol>
  <li>
    <strong>
      <a href="#">Link</a>
    </strong>
  </li>
</ol>
<!--XRAY END 37-->

NOTE: I am using xray-rails with rails 3.2 and it's working fine

Import html to rails method (in helper.rb)

I need piece of code for couple of times, and to follow DRY method (don't repeat yourself) i want to escape using this piece and retyping it for 5 times or more. So I want to define method what will contain both ruby and html, and ruby in html and js to, code. But I have problems with realization.

My html.erb look like this:

<% div_count = 1 %>
<div>
  <% for post in @posts %>
    <div class="post-on-main-page-<%= div_count %>"
         id="js-count-<%= div_count_for_js %>">
      <script>
        $("#js-count-<%= div_count_for_js %>").click(function(){
          window.location.href = "<%= post_url(post) %>";
        });
      </script>
    <%= image_tag(post.picture.url) %>
    <span><h5><%= post.theme %></h5></span>
  </div>
  <% end %>
<% div_count += 1 %>
<% if div_count == 4 %>
  <% div_count = 1 %>
<% end %>
</div>

And I want create method, I think in application_helper.rb will do with this piece of code. What will look something like that:

def method_name(parameter)
<% div_count = 1 %>
    <div>
      <% for post in parameter %>
        <div class="post-on-main-page-<%= div_count %>"
             id="js-count-<%= div_count_for_js %>">
          <script>
            $("#js-count-<%= div_count_for_js %>").click(function(){
              window.location.href = "<%= post_url(post) %>";
            });
          </script>
          <%= image_tag(post.picture.url) %>
          <span><h5><%= post.theme %></h5></span>
        </div>
      <% end %>
    <% div_count += 1 %>
    <% if div_count == 4 %>
      <% div_count = 1 %>
    <% end %>
  </div>
end

The result what I want for html.erb

<%= method_name(@posts)%>

How can I make this to work?