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.

Getting date parts from a simple treetop parser: wrong argument type Class (expected Module)

For the following treetop grammer, when parsing '3/14/01' (via t = Parser.parse('3/14/01') in irb), I get a "TypeError: wrong argument type Class (expected Module)".

grammar SimpleDate

  rule dateMDY
      whitespace? month_part ( '/' / '-') day_part ( ('/' / '-') year_part)? whitespace?  <DateMDY>
  end

  rule month_part
    ( ( '1' [0-2] ) / ( '0'? [1-9] ) )  <MonthLiteral>
  end

  rule day_part
    ( ( [12] [0-9] ) / ( '3' [0-1] ) / ( '0'? [1-9] ) ) <DayLiteral>
  end

  rule year_part
    ( ( '1' '9' ) / ( '2' [01] ) )? [0-9] [0-9]   <YearLiteral>   # 1900 through 2199 (4 digit)
  end

  rule whitespace
    [\s]+
  end

end

First, if I comment out the <MonthLiteral> and the <DayLiteral> class references, all is well. Commenting out <DateMDY>, but leaving those Literal objects in, will also issue the error. Commenting out <YearLiteral> does not seem to matter (it'll work or not work regardless) -- that seems to indicate that because the first two are non-terminal, I can't produce elements for them.

There is clearly something I'm not appreciating about how Ruby (or treetop) is instantiating these classes or about AST generation that would explain what happens. Can you explain or point me to something that can help me understand why <MonthLiteral> or <DayLiteral> can't have objects generated?

Second, this may be a bridge too far, but what I'd really prefer would be to get a DateMDY object with three attributes -- month, day, and year -- so I can readily produce a Ruby Time object from a method to_time in DateMDY, but right now I'd settle for just producing the constituent pieces as objects.

So I tried leaving <DateMDY> as the object and commented out the references to <MonthLiteral>, <DayLiteral>, and <YearLiteral>. I saw that the resulting AST object returned from .parse (t in my original example) has two public methods -- :day_part and :month_part but those seem to be nil when I invoke those (say, puts t.day_part) and there is no :year_part method, so that didn't seem to help me out.

Is it possible to do somehow have DateMDY end up accessing its constituent parts?

FYI, the Parser code itself I'm using is pretty standard stuff from the treetop tutorials and the node_extensions.rb that defines the object classes is also trivial, but I can post those too if you need to see those.

Thanks! Richard

undefined method 'body' for nil:Nilclass

I am writing integration test for my application. For the following test, I am getting

undefined method 'body' for nil:Nilclass

My RSpec code:

        it "should not make a new user" do
            visit signup_path
            fill_in "Name", :with => ""
            fill_in "Email", :with => ""
            fill_in "Password", :with => ""
            fill_in "Confirmation", :with => ""
            click_button "Sign up"
            response.should render_template('users/new')
            response.should have_selector("div#error_explanation")
        end

Controller:

class UsersController < ApplicationController
  def new
    @user = User.new
    @title = "Sign Up"
  end

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

  def create
    @user = User.new(user_params)
    if @user.save
    # Handle a successful save.
        flash[:success] = "Welcome to the Sample App!"
        redirect_to @user
    else
        @title = "Sign Up"
        render 'new'
    end
  end
  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end

What is missing/wrong in this code?

Show Certain Programs Depending On Certain Months

I am setting up an app that has certain programs that a user can subscribe to. These programs start and stop consecutively (example program A runs form Jan-March, program B runs to April-June, program C runs July-September and program D runs from October-December).

I would like to only display the programs open for subscribers when the month is present for the specific program or programs.

What is the proper method (Built in or to create) to set up in my views? I have read through the Ruby Date Api Docs (http://ift.tt/1woy8bR) but didnt find anything to suffice

Javascript event on form add fields

I've got a rails app using bootstrap with a form page that has the option to add additional form fields. The tutorial from this Railscast episode heavily influenced this form page add fields feature. I have a need to watch the add fields so that I can hide a warning panel in the new well created. Here is the code that will not work:

  $('#classifications_forms').on 'change', (event) ->
     container = $('.classifications_form').last()
     $('#premium-divide', container).hide()

I have tried an on click event for the add fields button, but it's late in the event watching as it will not hide the panel. If I hit the button a second time, it will hide the panel on the previously created well, so I know the code was working to hide the panel. My thinking is to hide the panel on the last well created, and I thought that a change on #classifications_forms would give me the event needed to hide the last well, but I guess its missing something on the event. What is missing above?

Rename everything to match new inflection after running a generator

I have a model in my rails app that has an irregular pluralisation. I know that I can fix this by adding the appropriate code to config/initializers/inflections.rb.

The problem is I didn't realise it was incorrect until after I ran a bunch of other generators and wrote a lot of code.

Is there any easy way (perhaps a gem?) to batch rename all my files, models, controllers, schema (via a migration I guess), etc to use the correct inflection?

Rspec Rails Testing for PublicActivity creation in controller test

I am testing the update method of a controller and part of the update creates a custom activity using the PublicActivity gem. When testing in Rspec the activities do not seem to be created. Here is the test that is failing:

it "creates a shared activity" do
      PublicActivity.with_tracking do
        expect{
            put :update, user_id: @michael, id: @michaels_task, task: FactoryGirl.attributes_for(:task, users_shared_to_ids: [@archer.id])
          }.to change(PublicActivity::Activity,:count).by(1)
      end
    end

I know that the put :update line works correctly as I can pass other tests looking for other changes relating to sharing the task.

Rails 4.2 Concern not included

I am trying to extend a module using Concern. The following file is saved as app/models/concerns/plutus_account_extenison.rb

module PlutusAccountExtension
  extend ActiveSupport::Concern

  included do
    belongs_to :party, class_name: 'V1::Party'
  end
end
Plutus::Account.send :include, PlutusAccountExtension

On load, the above concern is not included in Plutus::Account model. I can include the concern in rails console.

[1] pry(main)> Plutus::Account.reflect_on_all_associations(:belongs_to)
=> []


[2] pry(main)> Plutus::Account.send :include, PlutusAccountExtension
=> Plutus::Account (call 'Plutus::Account.connection' to establish a   connection)
[3] pry(main)> Plutus::Account.reflect_on_all_associations(:belongs_to)
=> [#<ActiveRecord::Reflection::BelongsToReflection:0x007fe9f5060130
  @active_record=Plutus::Account (call 'Plutus::Account.connection' to establish a connection),
  @association_scope_cache={},
  @automatic_inverse_of=nil,
  @constructable=true,
  @foreign_type="party_type",
  @klass=nil,
  @name=:party,
  @options={:class_name=>"V1::Party"},
  @plural_name="parties",
  @scope=nil,
  @scope_lock=#<Mutex:0x007fe9f507be08>,
  @type=nil>]

V

Rails Active Record .where statement optimization

I'm building an ecommerce site and want to use an active record where statement to find shipments that are scoped to a certain supplier and certain shipment states. Here's what I have now:

Spree::Shipment.where("stock_location_id = ? and "state = ?", spree_current_user.supplier.stock_locations.first.stock_location_id, 'shipped' || 'ready')

I've found that this results in only 'shipped' statements get returned. I'd like it to display both shipped, and ready shipments. So far I can only get it to show one or the other, depending on if i put 'shipped' or 'ready' first in the query.

I'm guessing I have put the OR operator (||) in the wrong place, even though there are no errors. Can someone tell me a proper way to place OR operators in a condition in the where statement?

Thanks,

  • Brandon

javascript scroll not working

I want my link to scroll down the page to the target content.

This is my script (inside the head tag):

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $(".scroll").click(function(event){     
            event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top},1200);
        });
    });
</script>

And these are my links (inside the body tag):

<%= link_to 'Plataformas', root_path + '#plataformas', class: "scroll" %>
<%= link_to 'Contato', root_path + '#contato', class: "scroll" %>

This chunks of code are inside my application.html.erb.

Thank you in advance!

Many-to-many controller on rails 4

I'm trying to do a many-check-box with a many-to-many association. I have tree models Empresa:

class Empresa < ActiveRecord::Base
  has_many :empresa_pagamento
  has_many :formas_pagamentos, :through =>  :empresa_pagamento
  has_one :tipo_restaurante
  has_many :produtos
end

Forma Pagamento

class FormaPagamento < ActiveRecord::Base
  has_many :empresa_pagamento
  has_many :empresas, :through => :empresa_pagamento

end

Empresa Pagamento

class EmpresaPagamento < ActiveRecord::Base
  belongs_to :empresa
  belongs_to :forma_pagamento

end

On my empresa_controller I have my params

def empresa_params
       params.require(:empresa).permit(:nome, :descricao, :cnpj, :razao_social,:formas_pagamentos, :tipo_restaurante)
end

When i try to save i do :

def create
    @empresa = Empresa.new(empresa_params)    
    respond_to do |format|
      if @empresa.save
         @empresa.formas_pagamentos.each do |forma_pagamento|
          empresa_pagamento = EmpresaPagamento.new
          empresa_pagamento.forma_pagamento = FormaPagamento.find(forma_pagamento)
          empresa_pagamento.empresa = @empresa
          empresa_pagamento.save
        end      
        format.html { redirect_to @empresa, notice: 'Empresa was successfully created.' }
        format.json { render :show, status: :created, location: @empresa }
      else
        format.html { render :new }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

on my _form i have

<div class="field">
    <%= f.label :formas_pagamentos %><br>
     <%= f.collection_select(:formas_pagamentos, FormaPagamento.all, :id, :nome,{:prompt => "Selecione"}, {:multiple => true}) %>

  </div>

Verify that user email is unique in test-unit rails

I a newbie in test-unit . I need to verify that email of the user is unique in the users table

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @usuario = User.new
    @usuario.email="pepe@hotmail.com"
    @usuario.password="123456"
  end 

  test "Verify that user email is unique" do

  end    
end

Nginx - Wordpress blog on Rails loads styles and scripts with mime type text/html

I just installed a Wordpress blog under a /blog directory within a Rails app, running on Unicorn and Nginx, and my stylesheets and scripts aren't being loaded properly in the browser when I go to my domain.com/blog pages. Chrome console's giving me the following error:

  • Resource interpreted as Stylesheet but transferred with MIME type text/html
  • Resource interpreted as Script but transferred with MIME type text/html

Have been trying to figure this out and tried out lots of solutions here on SO, but still can't get through... seems like there needs to be something changed on my Nginx config, particularly for the blog/php location. Here's my config:

upstream unicorn {
  server unix:/tmp/unicorn.domain.sock fail_timeout=0;
}

server {
  server_name www.domain.com;
  return 301 $http://ift.tt/1rlPdiI;
}

server {
  listen 80 default deferred;
  server_name domain.com;
  root /home/dcs/htdocs/domain/current/public;

  access_log /home/dcs/htdocs/domain/log/access.log;
  error_log  /home/dcs/htdocs/domain/log/error.log;


  location /blog {
    try_files $uri $uri/ /blog/index.php?$args;
  }

  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php-fpm.sock;

    fastcgi_index index.php;
    fastcgi_param  SCRIPT_FILENAME home/dcs/htdocs/domain/$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
  }


  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @unicorn;
  location @unicorn {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://unicorn;
  }

  error_page 500 502 503 504 /500.html;
  keepalive_timeout 10;
}

Displaying upvotes on different models together

I have upvotes working on posts and comments using the acts_as_votable gem. I display the posts and comments a user has upvoted like this:

@upvoted_posts = @user.get_voted Post
@upvoted_comments = @user.get_voted Comment

Is there a way that I can show the upvoted posts and comments together in one feed?

inserting a partial with infinite scroll

I have implemented the tutorial for infinite scroll as shown here http://ift.tt/1gFoqre

I however would like to render the partial for _formatted_posts.html.erb as opposed to just the generic _posts partial. If I change index.html.erb to

<div class="page-header">
  <h1>My posts</h1>
</div>

<div id="my-posts">
<% @posts.in_groups_of(3, false) do |posts| %>
    <div class="row padding-top-30">
      <% posts.each do |post| %>
          <div class="col-md-4">
            <%= render '_formatted_post', :post => post %>
          </div>
      <% end %>
    </div>    

<div id="infinite-scrolling">
  <%= will_paginate %>
</div>

It renders the first page of paginated posts fine, however as soon as it renders the second page of paginated posts it goes back to displaying it using the _posts.html.erb partial as opposed to _formatted_posts.html.erb

Does anyone have any advice on how to solve this problem?

All the best, Durham

Rails Where Clause PG::SyntaxError: ERROR: subquery must return only one column

I want to take advantage of rails scoping with a custom sql query. You can click this post for I'm trying to do - especially in ActiveAdmin.

How to use a find_by_sql query for an ActiveAdmin index page?

This is my query

LesleyGrade.where('select distinct STC_TERM_GPA, TERM, last, first from lesley_grades order by first, term ASC')

Essentially it's a subquery in a where clause. I only want to return a distinct STC_TERM_GPA for per person per row.

These are my attributes in a lesley_grades table, which might help in understand the information I'm trying to retrieve.

id
user_id
lesley_id
last
first
active
site
cohort
section
sections_title
faculty
completed_term_cred
term
sec_start_date
sec_end_date
grade
stc_cred
active_program
most_recent_program
intent_filed
stc_term_gpa
sta_cum_gpa
start_term
prog_status
last_change_date
created_at
updated_at

So I wanted to see if this would work in Rails C first and this is what I got.

  LesleyGrade Load (51.1ms)  SELECT "lesley_grades".* FROM "lesley_grades"  WHERE (select distinct STC_TERM_GPA,
    TERM,
    last,
    first
    from lesley_grades
order by first, term ASC)
PG::SyntaxError: ERROR:  subquery must return only one column
LINE 1: ...ECT "lesley_grades".* FROM "lesley_grades"  WHERE (select di...
                                                             ^
: SELECT "lesley_grades".* FROM "lesley_grades"  WHERE (select distinct STC_TERM_GPA,
    TERM,
    last,
    first
    from lesley_grades
order by first, term ASC)
=> #<LesleyGrade::ActiveRecord_Relation:0x3fcb44d60944>

I'm not sure how to fix

PG::SyntaxError: ERROR:  subquery must return only one column

Rails production: Google font imported is not loaded

Problem:

After seeing questions about this topic, I request your help.

/assets/stylesheets/styles.css: @import url("http://ift.tt/1cDTOkU");

When I run rails s on test or development, the font 'Merriweather' is loaded, but when I run server on production, the font is not loaded, but the styles.css is loaded.


What I've tried:

• To put @import url(...) in application.css or welcome.scss or bootstrap.css.scss

• To change @import url('http://fonts.google...') by @import url('//fonts.google...')

Aditional info:

application.css

 *= require_tree .
 *= require_self
 *= require 'styles'

Github: http://ift.tt/1OYQTvs

Migrating to XOAUTH2 and accessing other users unread message count in google apps for education

We've got a google apps for eduction domain, and until recently we were happily using gmail_xoath and imap to get other users unread email counts to display on their portal front page.

We've been using Nicolas' excellent gmail_xoauth gem found here.

http://ift.tt/1PnpBdd

And our code looked like this.

require 'gmail_xoauth'
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH', @email,
        :two_legged => true,
        :consumer_key => consumer_key,
        :consumer_secret => consumer_secret()
)
@messages_count = imap.status('INBOX', ['UNSEEN'])['UNSEEN']
imap.disconnect

Notice how we're using the consumer_key and the consumer_secret that we got from our google apps admin in the Manage OAuth key and secret for this domain section.

Now we need to upgrade to Oauth2. gmail_xoauth does support XOAUTH2, and I followed this procedure to test that.

Create a project in my google developer console, using the installed app option. I'm signed into google as a domain admin for our google apps domain.

Using this page, http://ift.tt/1kOBnzP, send off the client_id and client_secret to obtain an Access Token. During that process I give the application authority to access my email by a consent screen.

Stick that access_token into this code

require 'gmail_xoauth'
@access_token = "access_token"
@email = "my email address"
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', @email, @access_token)
@messages_count = imap.status('INBOX', ['UNSEEN'])['UNSEEN']
imap.disconnect

That works, happy days!!

The problem I now have, is how do I tell my google apps domain to allow that project to access other users email data, wihtout asking them if they wany to allow it?

I tried this approach

Sign into Google Domain Admin Console as an admin

Click on Security

CLick Show More

Click Advanced

Click Manage API CLient Access

Enter the Client ID of the project created

Enter the Scope for IMAP access, http://ift.tt/nP7iLr

Once that was done, I still hept getting Invalid Credentials errors when trying to count the number of messages in other users mailboxes, as denoted by their email address.

I'm pretty sure I've misread some docs somewhere, and I'm doing something stupid, but I can't seem to work out what it is.

I'm thinking that maybe adding the project like that to the google apps domain isn't the correct way of authorising an application to access other users data in the domain. I've seen service accounts mentioned, and migrating to Oauth2, and various other possible solutions, but can't get any of them to work.

What I'd really like to know is what is the suggested approach that definitely works, and then I'll concentrate on that.

If anyone has any advice tips links, anything at all, I'd be eternally grateful.

Matt

Creating user from rails console command?

I am newbie in Ruby, I am trying to install one app that says:

lobsters$ rails console
Loading development environment (Rails 4.1.8)

irb(main):001:0> User.create(:username => "test", :email => "test@example.com", :password => "test", :password_confirmation => "test", :is_admin => true, :is_moderator => true
irb(main):002:0> Tag.create(:tag => "test")

When I run rails console, it outputs "create some file" So how do I create user?

rails paperclip processors in lib requires restart for every change. Change on request?

I have paperclip processors in the lib directory. Everytime I make a change to them, I am required to restart. I've tried the following in the /config/application.rb but none work. When I didn't have paperclip processors, the 3rd one worked so that I didn't have to restart my server everytime. Now, I have to restart everytime. 0Any suggestions on how to reload processors on request?

These are the 3 I've tried:

config.autoload_paths += "#{Rails.root}/lib"

config.eager_load_paths += ["#{Rails.root}/lib"]

config.autoload_paths << Rails.root.join('lib')

Just in case, in my model I have the line:

has_attached_file :mls_pdf,  :styles => { :mls_pdf_processor => {:text_for => 'subject'} },
            :path => "#{Rails.root}/storage/:class/:attachment/:id_partition/:style/:filename",
            :url => "#{Rails.root}/storage/:class/:attachment/:id_partition/:style/:filename",
            processors: [:mls_pdf_processor]

my processors in lib/paperclip_processors/mls_pdf_processor.rb

module Paperclip
class MlsPdfProcessor < Processor

    require 'paperclip_processors/processor_helper.rb'
    # include PaperclipProcessors::ProcessorHelper

    def initialize( file, options = {}, attachment = nil )
        super
        @file = file
        @attachment     = attachment
        @mls_type       = options[:text_for]
        @current_format = File.extname(@file.path) 
        @basename       = File.basename(@file.path, '.*')
        @dst_file       = Tempfile.new([@basename, 'txt'])

        @receiver = PDF::Reader::RegisterReceiver.new
        @text = []                  # all text data from PDF    
        @type                       # type of pdf

    end

    def make
        @file
        File.open(@dst_file)
    end

end
end

Display money-rails value in nested form

I have a nested form where a user can add multiple instances of a class. This nested form is part of a larger wizard (multi-step form) where the user can go forwards and backwards through the process.

In my rails application I'm using the money rails gem. When a user goes backwards in the wizard, I'd like to populate the fields so they can see what they've previously entered. Up until now, I've had no issue doing this with other nested objects. However, displaying a money field is stumping me.

# the field
<%= f.text_field :guarantor_net_worth, :value => ( f.object.guarantor_net_worth_cents.nil? ? nil : f.object.guarantor_net_worth_cents ) %>

# In console when I see if there is a value assigned to an object that I'm testing
guarantor_net_worth_cents: 4564600, guarantor_net_worth_currency: "CAD"

The thing I can't seem to figure out is when I set :value => f.object.guarantor_net_worth_currency, the field displays CAD, but won't seem to display the cents. To debug futher, I used puts to see the ID's of the objects I was creating and searching them in console and they are being created properly with the values being passed through params as they should.

Nginx start page with rubber gem

I've used rubber to deploy my rails app on ec2. I'ts my first time. All it's done. But when I go on my domain, I can see the nginx start page.

I used the ~passenger_nginx_postgresql template.

What I'v did wrong ?

reguards, Louis Audéon.

Freezing/locking errors when running Apache2/Passenger with Rails 3/omniauth-openid

I'm migrating a rails app from Unicorn/nginx to Apache2/Passenger (v5 open source version) and am having issues with application timeouts during the login process and I'm not sure even the problem lies - apache or passenger, or omni-auth.

We use omniauth-openid as a rails engine for authentication - when you enter an email address it sends off a request to the openid engine in the same app, which will then authenticate you and return that status to the original request which completes the login process.

Although i have multiple passenger processes running (8 max currently) the second request (to the openid engine) seems to always go back to the original blocking/blocked process.

The second request will then eventually time out and fail at exactly 60 seconds. The only message I get back from openid is:

(open_id) Authentication failure! connection_failed encountered.

passenger-status doesn't show second (or any subsequent) login attempts as being queued, it just creates a session on the one of the other concurrent processes but the openid requests ares still locked/frozen until the first one times out.

I'm not sure if apache is something limiting the connections through to passenger, or if passenger is somehow directing all the login requests to the one passenger process.

Any one have any idea as to where I could look next?

My passenger conf:

LoadModule passenger_module /home/jav/.rvm/gems/ruby-2.2.2@i3pro/gems/passenger-5.0.7/buildout/apache2/mod_passenger.so PassengerRoot /home/jav/.rvm/gems/ruby-2.2.2@i3pro/gems/passenger-5.0.7 PassengerRuby /home/jav/.rvm/gems/ruby-2.2.2@i3pro/wrappers/ruby PassengerDefaultRuby /home/jav/.rvm/gems/ruby-2.2.2@i3pro/wrappers/ruby PassengerUserSwitching on PassengerDefaultUser jav PassengerDefaultGroup jav PassengerMaxPoolSize 8

My passenger-status results after 3 concurrent login requests.

No processes to start with:

Version : 5.0.7
Date    : 2015-05-06 11:27:12 +1200
Instance: KR4Jkewi (Apache/2.4.7 (Ubuntu) Phusion_Passenger/5.0.7)

 ----------- General information -----------
Max pool size : 8
Processes     : 0
Requests in top-level queue : 0

Three requests made - 3 processes started/processing a session, nothing in queue:

----------- Application groups -----------
Date    : 2015-05-06 11:50:07 +1200
----------- General information -----------
Max pool size : 8
Processes     : 4
Requests in top-level queue : 0
----------- Application groups -----------
/home/jav/code/voyager#default:
  App root: /home/jav/code/voyager
  Requests in queue: 0
  * PID: 19871   Sessions: 1       Processed: 0       Uptime: 22s
    CPU: 0%      Memory  : 145M    Last used: 22s ago
  * PID: 19879   Sessions: 1       Processed: 0       Uptime: 22s
    CPU: 0%      Memory  : 129M    Last used: 22s ago
  * PID: 19886   Sessions: 1       Processed: 0       Uptime: 22s
    CPU: 0%      Memory  : 121M    Last used: 22s ago
  * PID: 19894   Sessions: 0       Processed: 0       Uptime: 21s
    CPU: 0%      Memory  : 76M     Last used: 21s ago

After time out, The first process has processed 4 requests (with 3 timeouts), while the rest only have processed the one request after being locked:

Date    : 2015-05-06 11:51:03 +1200
----------- General information -----------
Max pool size : 8
Processes     : 4
Requests in top-level queue : 0
----------- Application groups -----------
/home/jav/code/voyager#default:
  App root: /home/jav/code/voyager
  Requests in queue: 0
  * PID: 19871   Sessions: 0       Processed: 4       Uptime: 1m 18s
    CPU: 0%      Memory  : 166M    Last used: 17s ago
  * PID: 19879   Sessions: 0       Processed: 1       Uptime: 1m 18s
    CPU: 0%      Memory  : 136M    Last used: 1m 18s ago
  * PID: 19886   Sessions: 0       Processed: 1       Uptime: 1m 18s
    CPU: 0%      Memory  : 129M    Last used: 1m 18s ago
  * PID: 19894   Sessions: 0       Processed: 0       Uptime: 1m 17s
    CPU: 0%      Memory  : 76M     Last used: 1m 17s ago

Rails API - Accessing JSON Message Body

I like to create an API that adds multiple products from the message body. The JSON would look like below:

{"products":[
    {"name":"playstation"}, 
    {"name":"xbox"}, 
    {"name":"bluray"}
]}

The call would go to:

http://localhost:3000/api/v1/products/AddProducts

I'd like to run through .each item within products and do a .create, something like below:

        def AddProducts             
            *each item*.each do |p|
                Product.Create(p)
            end             
        end

My question is - How do I access the JSON being passed into my controller?

Thanks

Getting user ID when calling an action

I have a table for doing CRUD operations on books, and also users can check in books (the checking out is done my a different controller)

At the moment the check in works for the book table, but I can't update user data - the integer of how many books they have loaned out

Here is part of my table:

    <% @books.each do |book| %>
    <tr>
        <td><%= book.title %></td>
        <td><%= book.author %></td>
        <td class ="onloan"><%= book.onloan %></td>
        <td><%= link_to 'show', book %> </td>
        <td><%= link_to 'edit', edit_book_path(book) %></td>
        <td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <td><%=  link_to 'Check in', check_in_path(book)%></td>
    </tr>
    <% end %>

What I want to add is something like

@user = User.find(params[:id])
@user.books_on_loan - 1

Here is the check in def of my controller:

def check_in
 Book.find(params[:id]).update_attribute(:onloan, 0)
 redirect_to root_path
end

What's happens in Ruby and Python? Why the variable wil be nil in if block in ruby ,but undefined in python?

This question already has an answer Confusion with the assignment operation inside a falsy `if` block

  if false
      y = 'hi'
   end

  puts y

In ruby y has been "defined" in the if block,it will be nil(why?). Remove that block and this gives an error.

But, in python

 if False:
   y = 'hi'

 print y

It will gives an error.

What's happens in Ruby and Python?

Express Hello World -- Heroku Foreman Returns Code 5, 'npm start' works just fine

I'm following a tutorial in which I created a simple "Hello World" in Express. The tutorial gets everything up and running locally just fine with 'npm start'. The tutorial then moves on to prepare for uploading code to Heroku via Toolbelt. Following the directions (so far as I can tell), I execute 'foreman start'. When I hit the localhost URI, I get the basic HTML I'm expecting, but no CSS (no doubt related to the ERR_CONNECTION_REFUSED outputs I see in the console window, which is probably related to the whole server being shut down). Looking at the output from the command line, there is the text:

exited with code 5
sending SIGKILL to all processes

I've searched Google for what Foreman's code 5 is, but didn't see anywhere that discussed code 5. I downloaded the source code for Foreman on http://ift.tt/L5wPH5, but still couldn't figure out what code 5 is (!?!?). I suspect I could work out the issue if I knew what code 5 meant. Anyone out there know what it is?

write rspec test based on age or date

I have a method that should return a category of member based on the age/date_of_birth. I want do write some test for that method because it a important method.

And my question is how can I test the model in order not failing the test in future because the date continuously changing.

I try to provide a pseudo test:

IF THE member IS > 18 => OUTPUT: "Adult"  
IF THE member IS < 15 => OUTPUT: "XYZ"

thanks

jquery javascript sorting

I am currently trying to build jquery filtering. Here is my part of my keyword filtering javascript code:

This is the problem:

<div class="task" data-task="#<Task:0x007fe319f71490>">
                  <ul>
                    <li>
                      <input name="task[5]" type="hidden" value="0"><input class="checkbox-task" type="checkbox" value="1" name="task[5]" id="task_5">
                      <label for="Some_Task0">Some task0</label>
                      <br>
                      <label for="Description">Description</label>
                      Finish this assessment.
                      <br>
                      <label for="Due_Date">Due date</label>
                      2015-06-22
                      <br>
                      <a class="btn btn-warning" href="/tasks/5/edit">Update Task</a>
                    </li>
                  </ul>
                </div>

The terms that are relevant to me are: 1) Some_Task0 2) Finish this assessment.

How can I obtain those words?

I currently am doing this:

$(task).find("label")

How to I specifically get those labels so I can get those values so I can then run a RegExp.test on the letter that I type into the search bar?

Avoiding eval when building radio buttons in rails

Here, I am building database driven radio buttons. I wanted to know if there is a way I can avoid eval and see checked is true or not !Thanks,

Index Controller

 columns = Model.column_names  

View in haml

- columns.each do |cols|
      - check = "c[0].#{cols}==1? true : false" // checking value here
      - negcheck = "c[0].#{cols}==0? true : false"// checking value here    
      - pluckid = "c[0].id"
      - id = eval(pluckid)
      %tbody
         %td #{cols}
         %td
          = label_tag 'On'
          = radio_button_tag("ABC",1,checked = eval(check), options = {})
          = label_tag 'Off'
          = radio_button_tag("xyz",0,checked = eval(negcheck), options = {})

How to only show previous & current level checkboxes?

When a user is on Level 1 how can we only show Level 1 checkboxes? If a user is on Level 2 how can we only show Level 2 & Level 1 checkboxes? Etc...

Right now it shows all 5 levels regardless of current level, which can be confusing for a user:

<label id="<%= @habit.id %>" class="habit-id"> Missed: </label>
  <% @habit.levels.each_with_index do |level, index| %>
    <p>
      <label id="<%= level.id %>" class="level-id"> Level <%= index + 1 %>: </label>
      <%= check_box_tag nil, true, level.missed_days > 0, {class: "habit-check"} %>
      <%= check_box_tag nil, true, level.missed_days > 1, {class: "habit-check"} %>
      <%= check_box_tag nil, true, level.missed_days > 2, {class: "habit-check"} %>
    </p>
  <% end %>

enter image description here

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
            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

habits_controller

class HabitsController < ApplicationController
  before_action :set_habit, only: [:show, :edit, :update, :destroy]
  before_action :logged_in_user, only: [:create, :destroy]

  def index
    if params[:tag]
      @habits = Habit.tagged_with(params[:tag])
    else
      @habits = current_user.habits.order("date_started DESC")
    end
  end

  def show
  end

  def new
    @habit = current_user.habits.build
  end

  def edit
  end

  def create
    @habit = current_user.habits.build(habit_params)
    if  @habit.save_with_current_level
        track_activity @habit
        redirect_to @habit, notice: 'Habit was successfully created.'
    else
        @feed_items = []
        render 'pages/home'
    end
  end

  def update
    if @habit.update(habit_params)
      redirect_to @habit, notice: 'Habit was successfully updated.'
    else
      render action: 'edit'
    end
  end

  def destroy
    @habit.destroy
    redirect_to habits_url
  end

  private
    def set_habit
      @habit = Habit.find(params[:id])
    end

    def correct_user
      @habit = current_user.habits.find_by(id: params[:id])
      redirect_to habits_path, notice: "Not authorized to edit this habit" if @habit.nil?
    end

  def habit_params
    params.require(:habit).permit(
      :user_id, 
      :trigger,
      :tag_list,
      :current_level,
      :missed_days,
      :target, 
      :reward,
      :comment,
      :private,
      :order,
      :date_started,
      :missed_one, 
      :committed => [],
      levels_attributes: [
      :missed_days])
  end
end

Here's the gist of it: http://ift.tt/1PISTF0

Thank you so much for your time! And if you have some spare time here's a similar problem: How to call a table column (t.integer) on a model method?