Affichage des articles dont le libellé est Active questions tagged ruby-on-rails - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged ruby-on-rails - Stack Overflow. Afficher tous les articles

mardi 5 mai 2015

When login in activeadmin, I get ther error

I use gem activeadmin. Every time, when I login, I get the error.

ActionController::ActionControllerError in ActiveAdmin::Devise::SessionsController#new

raise ActionControllerError.new("Cannot redirect to nil!") unless options

on url: http://localhost:3000/admin/login

But if I go to this url http://localhost:3000/admin activeadmin is working, but writing You are already signed in.

routes.rb

ActiveAdmin.routes(self)

#settings activeadmin
devise_for :admin_users, ActiveAdmin::Devise.config

#settings devise
devise_for :users, controllers: { sessions: "sessions", registrations: "registrations" }
get 'persons/profile'

application_controller.rb

  protect_from_forgery  with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

def after_sign_in_path_for(resource)
    request.referer
end

def after_sign_out_path_for(resource_or_scope)
    root_path
end

log

Started GET "/admin/login" for 127.0.0.1 at 2015-05-06 10:49:04 +0600
Processing by ActiveAdmin::Devise::SessionsController#new as HTML
  AdminUser Load (0.3ms)  SELECT  "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1  ORDER BY "admin_users"."id" ASC LIMIT 1  [["id", 2]]
Redirected to 
Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.3ms)

ActionController::ActionControllerError (Cannot redirect to nil!):
  actionpack (4.2.1) lib/action_controller/metal/redirecting.rb:70:in `redirect_to'
  actionpack (4.2.1) lib/action_controller/metal/flash.rb:57:in `redirect_to'
  actionpack (4.2.1) lib/action_controller/metal/instrumentation.rb:64:in `block in redirect_to'
  activesupport (4.2.1) lib/active_support/notifications.rb:164:in `block in instrument'
  activesupport (4.2.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.2.1) lib/active_support/notifications.rb:164:in `instrument'
  actionpack (4.2.1) lib/action_controller/metal/instrumentation.rb:63:in `redirect_to'
  devise (3.4.1) app/controllers/devise_controller.rb:110:in `require_no_authentication'
  activesupport (4.2.1) lib/active_support/callbacks.rb:432:in `block in make_lambda'
  activesupport (4.2.1) lib/active_support/callbacks.rb:145:in `call'
  activesupport (4.2.1) lib/active_support/callbacks.rb:145:in `block in halting_and_conditional'
  activesupport (4.2.1) lib/active_support/callbacks.rb:504:in `call'
  activesupport (4.2.1) lib/active_support/callbacks.rb:504:in `block in call'
  activesupport (4.2.1) lib/active_support/callbacks.rb:504:in `each'
  activesupport (4.2.1) lib/active_support/callbacks.rb:504:in `call'
  activesupport (4.2.1) lib/active_support/callbacks.rb:92:in `_run_callbacks'
  activesupport (4.2.1) lib/active_support/callbacks.rb:776:in `_run_process_action_callbacks'
  activesupport (4.2.1) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.2.1) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.2.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
  activesupport (4.2.1) lib/active_support/notifications.rb:164:in `block in instrument'
  activesupport (4.2.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.2.1) lib/active_support/notifications.rb:164:in `instrument'
  actionpack (4.2.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.2.1) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  searchkick (0.8.7) lib/searchkick/logging.rb:107:in `process_action'
  activerecord (4.2.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.2.1) lib/abstract_controller/base.rb:137:in `process'
  actionview (4.2.1) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.2.1) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.2.1) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.2.1) lib/action_controller/metal.rb:237:in `block in action'
  actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:74:in `call'
  actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
  actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:43:in `serve'
  actionpack (4.2.1) lib/action_dispatch/routing/mapper.rb:49:in `serve'
  actionpack (4.2.1) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.1) lib/action_dispatch/journey/router.rb:30:in `each'
  actionpack (4.2.1) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:819:in `call'
  warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.3) lib/warden/manager.rb:34:in `catch'
  warden (1.2.3) lib/warden/manager.rb:34:in `call'
  rack (1.6.0) lib/rack/etag.rb:24:in `call'
  rack (1.6.0) lib/rack/conditionalget.rb:25:in `call'
  rack (1.6.0) lib/rack/head.rb:13:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.0) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.0) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.1) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:649:in `call'
  activerecord (4.2.1) lib/active_record/migration.rb:378:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.1) lib/active_support/callbacks.rb:88:in `call'
  activesupport (4.2.1) lib/active_support/callbacks.rb:88:in `_run_callbacks'
  activesupport (4.2.1) lib/active_support/callbacks.rb:776:in `_run_call_callbacks'
  activesupport (4.2.1) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.1.2) lib/web_console/middleware.rb:37:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.1) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.1) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.1) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.1) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.1) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.1) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.0) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.0) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.0) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.1) lib/action_dispatch/middleware/static.rb:113:in `call'
  rack (1.6.0) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.1) lib/rails/engine.rb:518:in `call'
  railties (4.2.1) lib/rails/application.rb:164:in `call'
  rack (1.6.0) lib/rack/lock.rb:17:in `call'
  rack (1.6.0) lib/rack/content_length.rb:15:in `call'
  rack (1.6.0) lib/rack/handler/webrick.rb:89:in `service'
  /home/maratovich/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
  /home/maratovich/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
  /home/maratovich/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

Found many issues but not helped me

In ruby console, how to update instance variable?

I have a model named "Person". In ruby console, I first declare an instance of Person, then I update the attributes, then save.

person = Person.last
person.name = "jeff"
person.save

After doing these, I got message like this:

   (9.9ms)  BEGIN
   (7.5ms)  ROLLBACK
=> false

What are "BEGIN", "ROLLBACK", "false" refers to separately? I googled, but nothing came out.

WrapBootstrap template doesn't work

I just purchased a wrap bootstrap template and tried to use it on a ruby on rails app. I pasted all its images files under my local /app/assets/images folder, js files under /app/assets/javascripts , html files under /app/views and all css files under /app/assets/stylesheets.

When I just clicked the html file it's working correctly. But when I tried to run localhost, it just showed the basic html files without any pictures or font styles.

Push value to model when created - Rails

I am trying to set the inputter_id value automatically to the id for for the inputter_type corresponding to "Medical team" in a form if the user is a current_clinician:

  def create
    esas_assessment_params = params.require(:esas_assessment).permit(:patient_id, :clinician_id, :time, :year, :month, :day, :inputter_name, :inputter_id, :pain, :pain_comment, :tiredness, :tiredness_comment, :drowsiness, :drowsiness_comment, :nausea, :nausea_comment, :lack_of_appetite, :lack_of_appetite_comment, :shortness_of_breath, :shortness_of_breath_comment, :depression, :depression_comment, :wellbeing, :wellbeing_comment, :other_symptom_id, :other_symptom_score, :other_symptom_comment, :esas_comment)
    @esas_assessment = EsasAssessment.new(esas_assessment_params)
    if current_clinician
      @esas_assessment.clinician = current_user.clinician
      @esas_assessment.inputter_name = current_user.clinician.full_name
      @esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')
    else
      @esas_assessment.patient = current_user.patient
      @esas_assessment.clinician = current_user.patient.clinician
    end
    if @esas_assessment.save
      redirect_to esas_assessments_path, notice: "ESAS assessment submitted!"
    else
      render "new", alert: "ESAS assessment not submitted!"
    end
  end

or more simply:

  def create
    esas_assessment_params = params.require(:esas_assessment).permit!
    @esas_assessment = EsasAssessment.new(esas_assessment_params)

     @esas_assessment.inputter_id = Inputter.find_by(inputter_type: 'Medical team')

    if @esas_assessment.save
      redirect_to esas_assessments_path, notice: "ESAS assessment submitted!"
    else
      render "new", alert: "ESAS assessment not submitted!"
    end
  end

in the first example the lines to set the @esas_assessment.clinician value automatically to the current_user.clinician and setting the inputter_name both work but the inputter_id doesn't.

My EsasAssessment model is:

EsasAssessment:
  patient_id: integer
  clinician_id: integer
  created_at: datetime
  updated_at: datetime
  inputter_name: string
  inputter_id: integer

class EsasAssessment < ActiveRecord::Base
    belongs_to :other_symptom
    belongs_to :clinician
    belongs_to :patient
    belongs_to :inputter
end

Inputter is:

Inputter:
  inputter_type: string

class Inputter < ActiveRecord::Base
    has_many :esas_assessments
end

When I submit my form I don't get any errors or warning, inputter_id is just nil

if I enter

Inputter.find_by(inputter_type: 'Medical team')

in Console it returns

#<Inputter {"id"=>309, "inputter_type"=>"Medical team"}>

Any advice on how to get the value to stick to the new EsasAssessment would be great

Ruby rails can't add user entry

Everything seems to go fine and there's no error message when executing user.save, but it doesn't show up when indexing.

I ran the migration:

class AddEmailToUsers < ActiveRecord::Migration
  def change
    add_column :email, :name, :password, :password_confirmation, :string
  end
end

models/user.rb

class User < ActiveRecord::Base
  #attr_accessor :remember_token
  attr_accessor :email
  attr_accessor :name
  attr_accessor :password_digest
  attr_accessor :password, :password_confirmation
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
 # has_secure_password
  validates :password, length: { minimum: 6 }

  # functions...
end

Here on create I fill in some sample values to test it, and it submits to views/users/create.html.erb without anything displaying in "Error: []" and the correct data shown for the fields of @user.

controllers/user_controller.rb

class UsersController < ApplicationController
  def new
    #require 'bcrypt'
    @user = User.new
  end

  def index
    @users = User.all
  end

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

 def create
    #@user = User.new(user_params)
    @user = User.new(name: "di3", email:"di3@di3.com", password: "di3", password_confirmation: "di3")
    #@user = User.new(params[:user])
    if @user.save!
      log_in @user
      flash[:success] = "Welcome to the forum!"
      #redirect_to @user
      #redirect_to users_path
    else
      #render 'new'
      render @user.error_messages.full
    end
  end

  private

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

views/users/create.html.erb

<h1>Create user params</h1>

<%= render partial: 'layouts/header' %>

<table>
  <tr>
    <th>Email</th>
    <th>Name</th>
    <th>Password</th>
  </tr>

      <tr>
        <td><%= @user.email %></td>
        <td><%= @user.name %></td>
        <td><%= @user.password %></td>
        <td><%= @user.password_confirmation %></td>
      </tr>
</table>

<br/>

Error:

<%= @user.errors.full_messages %>

But this user index doesn't show any users at all:

views/users/index.html.erb

<h1>Listing forums</h1>

<%= render partial: 'layouts/header' %>

<table>
  <tr>
    <th>Email</th>
    <th>Name</th>
    <th>Password</th>
    <th>Password</th>
    <th>Password</th>
  </tr>

  <% if(@users)
    @users.each do |user| %>
      <tr>
        <td><%= user.email %></td>
        <td><%= user.name %></td>
        <td><%= user.password_digest %></td>
        <td><%= user.password %></td>
        <td><%= user.password_confirmation %></td>
      </tr>
    <% end %>
  <% end %>
</table>

Connection pool in Ruby on Rails using mongo Db

I am new to ruby on rails (using rails 4 and ruby 2.0.0). I found a few tutorials online for mongo db in RoR using mongoid.yml, but they give only the basic steps. I want to know how to make a connection pool and and use it.

What changes to do it the mongoid.yml?

And how to (in java terms)getConnection from the controller?

Any help would be appreciated

Thanks :)

Rails Rspec test that a controller has triggered Websockets event

In my controller I have the following code that triggers a websockets event inside the update method:

WebsocketRails[recipient.id].trigger "new_activity", "Shared" if recipient.online?

How can I test that my controller is triggering this event?

jQuery disable opposite input field IE8

I have a simple Rails 3 form with two separate input fields. If a user begins typing into one field, I would like the other field to immediately become disabled. This is fairly straightforward, and I currently have a working solution for IE9+, Chrome, FF, and Safari - using the code from this post: Disable opposite input if I type into another of a pair

However, it does not work in IE8 for some reason. Instead, as soon as the user begins typing, both fields are disabled and my form fails the jQuery validation (as if it was submitted early, even though the submit button has not been clicked).

My Form:

<%= form_tag instructor_profiles_path, :class => "form-inline", :role => "form", :method => :get, :id => "search" do %>

  <div class="form-group">
    <%= select_tag :search_miles, options_for_select(search_miles), :class => "form-control input-sm" %><span>&nbsp;&nbsp;Miles of&nbsp;</span>
    <%= text_field_tag :search_airport, params[:search_airport], :maxlength => 4,   :class => "form-control input-sm", :id => "AirportInputId", :placeholder => "Airport ID" %><span>&nbsp;&nbsp;or&nbsp;</span>
    <%= text_field_tag :search_zip_code, params[:search_zip_code], :maxlength => 5, :class => "form-control input-sm", :id => "ZipcodeInputId", :placeholder => "Zip code" %>
  </div>

  <%= submit_tag "Search!", :name => nil, class: "btn btn-primary btn-sm" %>

<% end %>

My jQuery:

$(document).ready(function() {

  // Validations for search form
  $('#search').validate({   
      rules: {
          search_airport: {
              rangelength:[3,4]
          },
          search_zip_code: {
              digits: true, 
              rangelength:[5,5]
          }
      }, // end rules
      messages: {
          search_airport: {
              rangelength: "Please enter a valid US Airport ID."
          },
          search_zip_code: {
              digits: "Please enter only digits for zip code.",
              rangelength: "Please enter a valid 5-digit zip code."
          }
      },
      // The following function is what places the error message after the entire form group
      errorPlacement: function(error, element) {
          error.appendTo( element.parents().eq(1) );
          error.addClass('error-message');          
      }     
  }); // end validate()

  // Disables the opposite input field so user cannot enter Airport ID AND Zip code
  function mutuallyExclusive( e ) { 

    var AIRPORTvalue = $('#AirportInputId').val();
    var ZIPCODEvalue = $('#ZipcodeInputId').val();

    if ( AIRPORTvalue.length > 0) {
      $('#ZipcodeInputId').prop("disabled", true);
    } else {
      $('#ZipcodeInputId').removeAttr("disabled");
    }

    if ( ZIPCODEvalue.length > 0) {
      $('#AirportInputId').prop("disabled", true);
    } else {
      $('#AirportInputId').removeAttr("disabled");
    }    

  }

  $( '#AirportInputId' ).on( 'change keyup', mutuallyExclusive );   
  $( '#ZipcodeInputId' ).on( 'change keyup', mutuallyExclusive );   

}); // end ready

Ruby / Brew Stopped Working Yosemite

I'm fairly new to this so hang with me..

I have been searching for a solution to this problem for a week now.

Ruby does not seem to be working

ruby
-bash: ruby: command not found

or

ruby -v
-bash: ruby: command not found

and whenever I try homebrew this is what comes back

/usr/local/bin/brew: /usr/local/Library/brew.rb:     /System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby: bad     interpreter: No such file or directory
/usr/local/bin/brew: line 21: /usr/local/Library/brew.rb: Undefined error: 0

as you can see above I had changed the ruby framework to read from 1.8 to Current as others had suggested, however this did not solve the problem as it did for users who had encountered the same issue.

So the search continues on...

My usr/local/bin/brew script looks like this -

#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby -W0
# encoding: UTF-8

std_trap = trap("INT") { exit! 130 } # no backtrace thanks

HOMEBREW_BREW_FILE = ENV['HOMEBREW_BREW_FILE']

if ARGV == %w{--prefix}
  puts File.dirname(File.dirname(HOMEBREW_BREW_FILE))
  exit 0
end

require 'pathname'
HOMEBREW_LIBRARY_PATH =     Pathname.new(__FILE__).realpath.dirname.parent.join("Library/Homebrew").to_s
$:.unshift(HOMEBREW_LIBRARY_PATH + '/vendor')
$:.unshift(HOMEBREW_LIBRARY_PATH)
require 'global'

case ARGV.first when '-h', '--help', '--usage', '-?', 'help', nil
  require 'cmd/help'
  puts Homebrew.help_s
  exit ARGV.first ? 0 : 1
when '--version'
  puts HOMEBREW_VERSION
  exit 0
when '-v'
  puts "Homebrew #{HOMEBREW_VERSION}"
  # Shift the -v to the end of the parameter list
  ARGV << ARGV.shift
  # If no other arguments, just quit here.
  exit 0 if ARGV.length == 1
end

   # Check for bad xcode-select before anything else, because `doctor` and
# many other things will hang
# Note that this bug was fixed in 10.9
if OS.mac? && `xcode-select -print-path 2>/dev/null`.chomp == '/' &&     MacOS.version < :mavericks
  ofail <<-EOS.undent
  Your xcode-select path is currently set to '/'.
  This causes the `xcrun` tool to hang, and can render Homebrew unusable.
  If you are using Xcode, you should:
    sudo xcode-select -switch /Applications/Xcode.app
  Otherwise, you should:
    sudo rm -rf /usr/share/xcode-select
 EOS

  exit 1
end

case HOMEBREW_PREFIX.to_s when '/', '/usr'
  # it may work, but I only see pain this route and don't want to support it
  abort "Cowardly refusing to continue at this prefix: #{HOMEBREW_PREFIX}"
end
if OS.mac? and MacOS.version < "10.5"
  abort <<-EOABORT.undent
    Homebrew requires Leopard or higher. For Tiger support, see:
    http://ift.tt/17h053J
  EOABORT
end

# Many Pathname operations use getwd when they shouldn't, and then throw
# odd exceptions. Reduce our support burden by showing a user-friendly error.
Dir.getwd rescue abort "The current working directory doesn't exist, cannot proceed."


def require? path
  require path.to_s.chomp
rescue LoadError => e
  # HACK :( because we should raise on syntax errors but
  # not if the file doesn't exist. TODO make robust!
  raise unless e.to_s.include? path
end

begin
  trap("INT", std_trap) # restore default CTRL-C handler

  aliases = {'ls' => 'list',
             'homepage' => 'home',
             '-S' => 'search',
             'up' => 'update',
             'ln' => 'link',
             'instal' => 'install', # gem does the same
             'rm' => 'uninstall',
             'remove' => 'uninstall',
             'configure' => 'diy',
             'abv' => 'info',
             'dr' => 'doctor',
             '--repo' => '--repository',
             'environment' => '--env',
             '-c1' => '--config',
             }

  cmd = ARGV.shift
  cmd = aliases[cmd] if aliases[cmd]

  sudo_check = Set.new %w[ install link pin unpin upgrade ]

  if sudo_check.include? cmd
    if Process.uid.zero? and not File.stat(HOMEBREW_BREW_FILE).uid.zero?
      raise "Cowardly refusing to `sudo brew #{cmd}`\n#{SUDO_BAD_ERRMSG}"
    end
  end

  # Add contributed commands to PATH before checking.
  ENV['PATH'] += ":#{HOMEBREW_CONTRIB}/cmd"
  if require? HOMEBREW_REPOSITORY/"Library/Homebrew/cmd"/cmd
    Homebrew.send cmd.to_s.gsub('-', '_').downcase
  elsif which "brew-#{cmd}"
    %w[CACHE CELLAR LIBRARY_PATH PREFIX REPOSITORY].each do |e|
      ENV["HOMEBREW_#{e}"] = Object.const_get "HOMEBREW_#{e}"
    end
    exec "brew-#{cmd}", *ARGV
  elsif require? which("brew-#{cmd}.rb").to_s
    exit 0
  else
    onoe "Unknown command: #{cmd}"
    exit 1
  end

rescue FormulaUnspecifiedError
  abort "This command requires a formula argument"
rescue KegUnspecifiedError
  abort "This command requires a keg argument"
rescue UsageError
  onoe "Invalid usage"
  abort ARGV.usage
rescue SystemExit
  puts "Kernel.exit" if ARGV.verbose?
  raise
rescue Interrupt => e
  puts # seemingly a newline is typical
  exit 130
rescue BuildError => e
  e.dump
  exit 1
rescue RuntimeError, SystemCallError => e
  raise if e.message.empty?
  onoe e
  puts e.backtrace if ARGV.debug?
  exit 1
rescue Exception => e
  onoe e
  puts "#{Tty.white}Please report this bug:"
  puts "    #{Tty.em}#{ISSUES_URL}#{Tty.reset}"
  puts e.backtrace
  exit 1
else
  exit 1 if Homebrew.failed?
end

    enter code here

Does any of this make sense or ring any bells? Could it have anything to do with why I'm getting the Homebrew or Ruby error?

Any help would be greatly appreciated.

I'd be happy to provide as much information as possible for us to solve this problem! :)

Ruby on rails access Devise.sign_in_after_reset_password in a controller

Im overriding Devise's Devise::PasswordsController, so i can use it as a RESTful web service. For that, i've overridden all four methods (new, create, edit and update), based in devise's original Devise::PasswordsController class. It's been straight forward except for the update method, which uses a devise attribute called Devise.sign_in_after_reset_password. I've found that it is defined in the library module, but when I try to access it, i get the following error:

NoMethodError in Api::V1::PasswordsController#update

undefined method `sign_in_after_reset_password' for Devise:Module

Extracted source (around line #37):
36    resource.unlock_access! if unlockable?(resource)
37    if Devise.sign_in_after_reset_password
38      flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
39      set_flash_message(:notice, flash_message) if is_flashing_format?
40      sign_in(resource_name, resource)

So far, I tried to require 'devise', but it didn't work. I googled it for a while, but didn't find anything either. Im kind of new to ruby and to ruby on rails, so I don't really know where to look. Any help would be very appreciated. Im using RoR 4.2.1 and Ruby 2.2.1 (2015-02-26)

Rails: uninitialized constant Model::RenamedAssociation when using class to specify model in relationship

I have 3 tables, Charges, Transactions and Charges_Transactions.

I had to rename the associations on my models as there is an existing transactions method which was interfering with the association. See this article

class Charge < ActiveRecord::Base
  has_and_belongs_to_many :payment_transactions, join_table: "charges_transactions", foreign_key: "charge_id",
      association_foreign_key: "transaction_id", class: 'Transaction'
end

class Transaction < ActiveRecord::Base
  has_and_belongs_to_many :charges, join_table: "charges_transactions", foreign_key: "transaction_id",
      association_foreign_key: "charge_id"
end

@charge.payment_transactions

Now when I try to access the associated transactions for any charge I get the error:

uninitialized constant Charge::PaymentTransaction

Can I add CSS instead of css file to TinyMCE editor + rails?

Actually In my my application I have dynamic css for each document which is opening in the tinyMCE editor for editing but its not loading my styles or is there any way to pass a css to TinyMCE instead of content_css, because content_css accept only css files and I don't have any css file, my css is stored in the database for each document, so I want to apply css which is stored in the database to the content of TinyMCE editor

From ActiveRecord to S3

I am new to S3 and Rails so got stuck. I am wondering if I can directly pass object to S3.

My controller:

def start_upload
  @forecasts = Forecast.all
  Forecast.export_to_s3(@forecasts) 
end

Model:

def self.export_to_s3(data)
  ---AWS configs ---
  Aws.config = { :access_key_id => aws_access_key, :secret_access_key => aws_secret_access_key, :region => aws_region }

  s3 = Aws::S3::Client.new(region:aws_region)

   resp = s3.put_object(
     :bucket => aws_bucket,
     :key => aws_bucket_key_forcast,
     :body => IO.read(data)
   )
end

Using rack-cors with Rackspace CDN issues

I have a rails 4.2 app using rack-cors. None of my font-awesome icons show up even though all my other assets are fine. I'm using the rackspace cdn. My CDN url looks something like

http://ift.tt/1GYkfDb

My rack-cors config is in my config/application.rb

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins 'localhost:3000', /^http:\/\/\w+.+rackcdn.com/
    resource '/assets/*', headers: :any, methods: :get
  end
end

The icons show up locally just fine. It's only in production that they don't show. Any ideas on what I might be missing?

How to count current level missed_days?

How can we call something like this <%= habit.current_level.missed_days %> where we only call the missed_days from the current_level, instead of all the missed_days in a habit (to just give an general idea of what we want).

For example if two boxes are checked, calling <%= habit.missed_days %> in the habits index will show 2 and if eight boxes are checked it will show 8, but the goal here is that even if 8 boxes are checked:

enter image description here

it will still only say 2 strikes in the index because we are trying to only count the missed_days from the current level.

enter image description here

class Habit < ActiveRecord::Base
    belongs_to :user
    has_many :comments, as: :commentable
    has_many :levels
    serialize :committed, Array
    validates :date_started, presence: true
    before_save :current_level
    acts_as_taggable
    scope :private_submit, -> { where(private_submit: true) }
    scope :public_submit, -> { where(private_submit: false) }

attr_accessor :missed_one, :missed_two, :missed_three

    def save_with_current_level
        self.levels.build
        self.levels.build
        self.levels.build
        self.levels.build
        self.levels.build
        self.save
    end

    def self.committed_for_today
    today_name = Date::DAYNAMES[Date.today.wday].downcase
    ids = all.select { |h| h.committed.include? today_name }.map(&:id)
    where(id: ids)
  end 

    def current_level
            return 0 unless date_started
            committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
            n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday } - self.missed_days

      case n_days     
          when 0..9
            1
          when 10..24
            2
          when 25..44
            3
          when 45..69
            4
          when 70..99
            5
          else
            "Mastery"
        end
    end
end

We have t.integer "missed_days", default: 0 in the levels & habits tables.

Much of missed_days logic can be traced to its controller:

class DaysMissedController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days + 1
    habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days + 1
    level.save!
    head :ok # this returns an empty response with a 200 success status code
  end

  def destroy
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days - 1
    habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days - 1
    level.save!
    head :ok # this returns an empty response with a 200 success status code
  end
end

The gist of it: http://ift.tt/1PISTF0

Thank you for your awesomeness!

Rails 4.2 redirect status 200?

I'm writing an application in Rails 4.2 and my controller is as follows:

class PostsController < ApplicationController
before_action :require_admin, :except => [:index]

def index
  @posts = Post.all
end

def show
  @post = Post.find(params[:id])
end

def new
  @post = Post.new
end

def require_admin
  unless user_signed_in? && current_user.admin?
    flash[:alert] = 'You require admin privileges for editing posts'
    redirect_to root_path
  end
end

so when I use a rest client to send request to show or new before signing in, I'm being redirected to the signin page which is what I want and on signing in as a non-admin, I'm being redirected to the root path, which is also what I want, however, in both cases, the status code is 200 (should it not be 302?) which is quite unexpected, I'm trying to write tests for the controller and I'm having a hard time testing the redirects, the tests fail with Expected <redirect>, got <200> Can anyone please help me in pointing out to what's going on here?

I'm using devise for authentication

Counting the Days from the current_level?

There are 5 levels.

Each level has a certain amount of days in it that must pass before the habit can move up to the next level (as broken down by n_days):

      case n_days     
          when 0..9
            1
          when 10..24
            2
          when 25..44
            3  #Level 3
          when 45..69
            4
          when 70..99
            5
          else
            "Mastery"
         end
      end

How can we call the n_days from the present level in the habits index with something like <%= habit.current_level.n_days.count_off_from_zero_to_show %>?

For example, if we are specifically at 50 on level 3 it would show Day 5 in the habits index.

habit.rb

class Habit < ActiveRecord::Base
    belongs_to :user
    has_many :comments, as: :commentable
    has_many :levels
    serialize :committed, Array
    validates :date_started, presence: true
    before_save :current_level
    acts_as_taggable
    scope :private_submit, -> { where(private_submit: true) }
    scope :public_submit, -> { where(private_submit: false) }

attr_accessor :missed_one, :missed_two, :missed_three

    def save_with_current_level
        self.levels.build
        self.levels.build
        self.levels.build
        self.levels.build
        self.levels.build
        self.save
    end

    def self.committed_for_today
    today_name = Date::DAYNAMES[Date.today.wday].downcase
    ids = all.select { |h| h.committed.include? today_name }.map(&:id)
    where(id: ids)
  end 

    def current_level_strike
      levels[current_level - 1] # remember arrays indexes start at 0
    end

    def current_level
            return 0 unless date_started
            committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
            n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday } - self.missed_days

      case n_days     
          when 0..9
            1
          when 10..24
            2
          when 25..44
            3
          when 45..69
            4
          when 70..99
            5
          else
            "Mastery"
        end
    end
end

level.rb

class Level < ActiveRecord::Base
  belongs_to :habit
end

schema

create_table "habits", force: true do |t|
  t.integer  "missed_days",    default: 0
  t.text     "committed"
  t.integer  "days_lost",   default: 0
  t.datetime "date_started"
  t.string   "trigger"
  t.string   "target"
  t.string   "reward"
  t.boolean  "private_submit"
  t.integer  "user_id"
  t.datetime "created_at",                 null: false
  t.datetime "updated_at",                 null: false
  t.integer  "order"
end

add_index "habits", ["user_id", "created_at"], name: "index_habits_on_user_id_and_created_at"
add_index "habits", ["user_id"], name: "index_habits_on_user_id"

create_table "levels", force: true do |t|
  t.integer  "habit_id"
  t.integer  "days_lost",   default: 0
  t.integer  "missed_days",   default: 0
  t.integer  "current_level"
  t.datetime "created_at",                null: false
  t.datetime "updated_at",                null: false
end

add_index "levels", ["habit_id"], name: "index_levels_on_habit_id"

The Gist of it: http://ift.tt/1PISTF0

Attempting to run background task in Rails and use AJAX to update progress works in development, not in production

I have a long simulation which takes a while to complete, anywhere from a few seconds to several minutes depending on how many trials my user chooses to run. I'm using the gem 'spawnling' to run the simulation in the background, and using AJAX to every second query for the current progress to inform the user. I have a form which I submit remotely, which then creates a model which is used to store the progress and the data. After submitting the form remotely, I use the gem 'gon' to periodically check on the progress. When it reaches 100%, it stops watching and makes an AJAX call to return a HighChart showing the results of the simulation and inserts it into the page.

In development, it works exactly as I want. If I look at the log, upon submission of the form, the simulation starts, I get redirected, it returns, and I begin watching the progress.

Started PATCH "/sim_results/276" for 127.0.0.1 at 2015-05-05 16:03:47 -0400
Processing by SimResultsController#update as JS
  Parameters: {"utf8"=>"✓", "round"=>"1", "daily_doubles_remaining"=>"1", "trials"=>"100000", "scores"=>["0", "0", "0"], "buzzer_ratings"=>["1.0", "1.0", "1.0"], "confidence_ratings"=>["0.0", "0.0", "0.0"], "buzz_in_knowledge_ratings"=>["0.0", "0.0", "0.0"], "dd_fj_knowledge_ratings"=>["0.0", "0.0", "0.0"], "clues"=>["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29"], "daily_double"=>"", "previous_daily_double"=>"", "sim_result_id"=>"", "commit"=>"Simulate", "id"=>"276"}
Simulation starting.
Redirected to http://localhost:3000/sim_results/276
Simulation trial starting: 0.
Completed 302 Found in 27ms (ActiveRecord: 0.8ms)
Started GET "/sim_results/276" for 127.0.0.1 at 2015-05-05 16:03:47 -0400
Processing by SimResultsController#show as JS
  Parameters: {"id"=>"276"}
  Rendered sim_results/_loading.html.erb (0.4ms)
Completed 200 OK in 13ms (Views: 6.9ms | ActiveRecord: 0.4ms)
Simulation trial starting: 10.
Simulation trial starting: 20.
Simulation trial starting: 30.
Started GET "/sim_results/276?_method=get&gon_return_variable=true&gon_watched_variable=progress" for 127.0.0.1 at 2015-05-05 16:03:48 -0400
Processing by SimResultsController#show as */*
  Parameters: {"gon_return_variable"=>"true", "gon_watched_variable"=>"progress", "id"=>"276"}
Completed 200 OK in 11ms (Views: 0.2ms | ActiveRecord: 8.5ms)
Simulation trial starting: 40.
Simulation trial starting: 50.
Simulation trial starting: 60.
Started GET "/sim_results/276?_method=get&gon_return_variable=true&gon_watched_variable=progress" for 127.0.0.1 at 2015-05-05 16:03:49 -0400
Processing by SimResultsController#show as */*
  Parameters: {"gon_return_variable"=>"true", "gon_watched_variable"=>"progress", "id"=>"276"}
Completed 200 OK in 3ms (Views: 0.1ms | ActiveRecord: 0.2ms)
Simulation trial starting: 70.
Simulation trial starting: 80.
Simulation trial starting: 90.
Started GET "/sim_results/276?_method=get&gon_return_variable=true&gon_watched_variable=progress" for 127.0.0.1 at 2015-05-05 16:03:50 -0400
Processing by SimResultsController#show as */*
  Parameters: {"gon_return_variable"=>"true", "gon_watched_variable"=>"progress", "id"=>"276"}
Completed 200 OK in 6ms (Views: 0.1ms | ActiveRecord: 0.2ms)
Started GET "/sim_results/276" for 127.0.0.1 at 2015-05-05 16:03:50 -0400
Processing by SimResultsController#show as */*
  Parameters: {"id"=>"276"}
  Rendered sim_results/_results.html.erb (5.4ms)
Completed 200 OK in 21ms (Views: 15.7ms | ActiveRecord: 0.2ms)

However, in production, it's another story.

I, [2015-05-05T19:51:45.457240 #25489]  INFO -- : Started PATCH "/sim_results/23" for 24.93.22.1 at 2015-05-05 19:51:45 +0000
I, [2015-05-05T19:51:45.459666 #25489]  INFO -- : Processing by SimResultsController#update as JS
I, [2015-05-05T19:51:45.459783 #25489]  INFO -- :   Parameters: {"utf8"=>"✓", "round"=>"1", "daily_doubles_remaining"=>"1", "trials"=>"100000", "scores"=>["0", "0", "0"], "buzzer_ratings"=>["1.0", "1.0", "1.0"], "confidence_ratings"=>["0.0", "0.0", "0.0"], "buzz_in_knowledge_ratings"=>["0.0", "0.0", "0.0"], "dd_fj_knowledge_ratings"=>["0.0", "0.0", "0.0"], "clues"=>["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29"], "daily_double"=>"", "previous_daily_double"=>"", "sim_result_id"=>"", "commit"=>"Simulate", "id"=>"23"}
I, [2015-05-05T19:51:45.465148 #25489]  INFO -- : Simulation starting.
I, [2015-05-05T19:51:45.468300 #25489]  INFO -- : Redirected to http://ift.tt/1dM5nOA
I, [2015-05-05T19:51:45.468559 #25489]  INFO -- : Completed 302 Found in 9ms (ActiveRecord: 3.3ms)
I, [2015-05-05T19:51:45.490673 #25512]  INFO -- : Simulation trial starting: 0.
I, [2015-05-05T19:51:45.938886 #25512]  INFO -- : Simulation trial starting: 10.
I, [2015-05-05T19:51:46.367241 #25512]  INFO -- : Simulation trial starting: 20.
I, [2015-05-05T19:51:46.767434 #25512]  INFO -- : Simulation trial starting: 30.
I, [2015-05-05T19:51:47.215977 #25512]  INFO -- : Simulation trial starting: 40.
I, [2015-05-05T19:51:47.748930 #25512]  INFO -- : Simulation trial starting: 50.
I, [2015-05-05T19:51:48.218826 #25512]  INFO -- : Simulation trial starting: 60.
I, [2015-05-05T19:51:48.640786 #25512]  INFO -- : Simulation trial starting: 70.
I, [2015-05-05T19:51:49.267435 #25512]  INFO -- : Simulation trial starting: 80.
I, [2015-05-05T19:51:49.774944 #25512]  INFO -- : Simulation trial starting: 90.
I, [2015-05-05T19:51:50.310229 #25489]  INFO -- : Started GET "/sim_results/23" for 24.93.22.1 at 2015-05-05 19:51:50 +0000
I, [2015-05-05T19:51:50.312388 #25489]  INFO -- : Processing by SimResultsController#show as JS
I, [2015-05-05T19:51:50.312446 #25489]  INFO -- :   Parameters: {"id"=>"23"}
I, [2015-05-05T19:51:50.319312 #25489]  INFO -- :   Rendered sim_results/_results.html.erb (1.4ms)
I, [2015-05-05T19:51:50.319558 #25489]  INFO -- : Completed 200 OK in 7ms (Views: 3.7ms | ActiveRecord: 1.2ms)
I, [2015-05-05T19:51:51.495898 #25489]  INFO -- : Started GET "/sim_results/23?_method=get&gon_return_variable=true&gon_watched_variable=progress" for 24.93.22.1 at 2015-05-05 19:51:51 +0000
I, [2015-05-05T19:51:51.498151 #25489]  INFO -- : Processing by SimResultsController#show as */*
I, [2015-05-05T19:51:51.498205 #25489]  INFO -- :   Parameters: {"gon_return_variable"=>"true", "gon_watched_variable"=>"progress", "id"=>"23"}
I, [2015-05-05T19:51:51.501890 #25489]  INFO -- : Completed 200 OK in 4ms (Views: 0.1ms | ActiveRecord: 1.3ms)
I, [2015-05-05T19:51:51.573814 #25489]  INFO -- : Started GET "/sim_results/23" for 24.93.22.1 at 2015-05-05 19:51:51 +0000
I, [2015-05-05T19:51:51.575459 #25489]  INFO -- : Processing by SimResultsController#show as */*
I, [2015-05-05T19:51:51.575501 #25489]  INFO -- :   Parameters: {"id"=>"23"}
I, [2015-05-05T19:51:51.580973 #25489]  INFO -- :   Rendered sim_results/_results.html.erb (1.1ms)
I, [2015-05-05T19:51:51.581126 #25489]  INFO -- : Completed 200 OK in 6ms (Views: 2.9ms | ActiveRecord: 1.2ms)

It might be a little hard to follow, but basically, look at how in my development log, the 302 redirect status is immediately followed by GET "/sim_results/#id", and then Completed 200 OK. In development, the 302 redirect happens, but then only after the simulation finishes does the GET "sim_results/#id" start, which then finishes the remote form submit, which then triggers my JavaScript callback function to check for progress. This obviously defeats the whole purpose of checking for progress in the first place since the first time it checks, the progress is at 100%.

In development, this works both using the default WEBrick server and when I switched over to using puma, both running OSX. In production, I'm using AWS Elastic Beanstalk with Amazon Linux 1.1 and Puma. Any thoughts why my redirect is waiting for the background task to complete?

Edit: I probably should have added my redirect code, it's pretty simple but it looks like this:

def update
  result = sim_result
  result.data = {progress: 0}.to_yaml
  result.save

  Spawnling.new do 
    simulate_games()
  end

  redirect_to action: "show", id: params[:id] 
end

In my show method, if the simulation isn't finished it outputs the current progress, and if it is finished, it outputs the results.

Edit again:

I had the thought to see if the redirect was the problem or not, and replace it with a render call, essentially duplicating my show method:

def update
  result = sim_result
  result.data = {progress: 0}.to_yaml
  result.save

  Spawnling.new do 
    simulate_games()
  end
  @progress = "0"
  render partial: "sim_results/loading"
  #redirect_to action: "show", id: params[:id] 
end

Same thing, the ajax:success method doesn't fire until after the simulation finishes.

I, [2015-05-06T00:01:54.729274 #27944]  INFO -- :   Rendered sim_results/_loading.html.erb (0.7ms)
I, [2015-05-06T00:01:54.729634 #27944]  INFO -- : Completed 200 OK in 12ms (Views: 4.7ms | ActiveRecord: 3.5ms)
I, [2015-05-06T00:01:55.180999 #27989]  INFO -- : Simulation 10% done.
I, [2015-05-06T00:01:55.622344 #27989]  INFO -- : Simulation 20% done.
I, [2015-05-06T00:01:56.061575 #27989]  INFO -- : Simulation 30% done.
I, [2015-05-06T00:01:56.501373 #27989]  INFO -- : Simulation 40% done.
I, [2015-05-06T00:01:56.969043 #27989]  INFO -- : Simulation 50% done.
I, [2015-05-06T00:01:57.416849 #27989]  INFO -- : Simulation 60% done.
I, [2015-05-06T00:01:57.869045 #27989]  INFO -- : Simulation 70% done.
I, [2015-05-06T00:01:58.324920 #27989]  INFO -- : Simulation 80% done.
I, [2015-05-06T00:01:58.985362 #27989]  INFO -- : Simulation 90% done.
I, [2015-05-06T00:01:59.425573 #27989]  INFO -- : Simulation 100% done.
I, [2015-05-06T00:02:00.562305 #27944]  INFO -- : Started GET "/sim_results/29?_method=get&gon_return_variable=true&gon_watched_variable=progress" for 24.93.22.1 at 2015-05-06 00:02:00 +0000

So, it's not the redirect which is causing the problem.

NoMethodError in Blog::PostsController#create

Note: Rails newb here.

So, I recently created a Rails app with mongoid gem for use of MongoDB. I have a namespace route of :blog with a nest of resource of posts

Routes.rb:

Rails.application.routes.draw do
  namespace :blog do
    resources :posts
  end
end

The error comes from app/controllers/blog/post_controller.rb:

Class Blog::PostController < ApplicationController
  def create
   @post = Post.new(post_params)

  if @post.save
    redirect_to @post
  else
    render 'new'
  end
 end
end

I also have a 'post' model that comes with a title and body:

Class Post
 include Mongoid::Document
 field :title, type: String
 field :body, type: String
end

In new.html.erb:

<h1>Rails Sample Blog</h1>

<%= form_for :post, url: blog_post_path do |f| %>
  <div><%= f.label :title %><%= f.text_field :title %></div>
  <div><%= f.label :body %><%= f.text_area :body %></div>
<% end %>

Is there something I left out that I didn't catch? It's slowly haunting me.

unable to obtain stable firefox connection in 60 seconds (not version related?)

I just installed selenium-webdriver (2.45.0) to use with capybara (2.4.0) for feature testing (version from bundle show). I removed the version number from my gemfile for these two to ensure I am getting the latest versions. When I got this error, I searched SO and subsequently downgraded Firefox to version 33.

I have read through all of the "unable to obtain stable firefox connection in 60 seconds" posts on SO and the theme is generally the same - the version of selenium-webdriver does not work with the latest version of Firefox. Unfortunately, I have tried everything suggested and still get the same error.

Is there some other (very basic) thing I may be missing (bearing in mind that I just started with selenium)? Note also that I am using the Cloud9 IDE.

Thanks in advance for your help and suggestions.