Saturday, March 19, 2016

Create action not being called in form | Fixed issues

Create action not being called in form | Fixed issues


Create action not being called in form

Posted: 19 Mar 2016 06:55 AM PDT

I've just started a new app where I want to take a postcode in a form and save it to the database. My problem is that the create action doesn't seem to be being called no matter what I try.

Routes:

root 'postcodes#new'  resources :postcodes, only: [:new ,:create]  

Controller: postcodes_controller.rb

class PostcodesController < ApplicationController    def new      @postcode = Postcode.new    end      def create      @postcode = Postcode.new(postcode_params)      if @postcode.save        flash[:success] = 'Success'      else        flash[:error] = 'Error'      end    end      private      def postcode_params      params.require(:postcode).permit(:code)    end  end  

Model: postcode.rb

class Postcode < ApplicationRecord    validates :code, presence: true, uniqueness: true  end  

View: postcodes/new.haml

.container    %form      %fieldset.form-group        = form_for @postcode do |f|            = f.label :postcode            = f.text_field :code, placeholder: 'Example Postcode', class: 'form-control'          = f.submit 'Submit', class: 'btn btn-primary'  

I've attempted to pass more options in the form_for such as the method and action and now I have a feeling it's a routing error.

Any help will be appreciated.

Thanks.

MySQL REGEXP using Rails ActiveRecord

Posted: 19 Mar 2016 06:53 AM PDT

This has been bugging me for a while now... I need to query a table of users and find those that have a double space in the name. I have multiple versions of SQL queries that work directly against the db, the simplest and more succinct being:

SELECT 'first  last' REGEXP '[[:space:]]{2}';  

I can also make it work from rails using ruby REGEX:

User.pluck(:full_name).select {|n| n =~ /([[:alpha:]]*)[[:space:]]{2}/ }  

OR

User.pluck(:full_name).select {|n| n =~ /\w+\s{2}/ }  

I have been trying to use AR where in several ways, but I am not sure what I am missing. Maybe I need to escape something... I read a few times: http://dev.mysql.com/doc/refman/5.0/en/regexp.html

I just don't see why it doesn't work

2] pry(main)> User.where("'full_name' REGEXP ?", "[[:alpha:]]*[[:space:]]{2}").count  => 0  [3] pry(main)> User.where("'full_name' REGEXP ?", '[[:alpha:]]*[[:space:]]{2}').count  => 0  [4] pry(main)> User.where("'full_name' REGEXP ?", '[[:alpha:]]*[[:space:]]{2}').to_sql  => "SELECT `users`.* FROM `users` WHERE ('full_name' REGEXP '[[:alpha:]]*[[:space:]]{2}')"  [5] pry(main)> User.where("'full_name' REGEXP ?", '[[:space:]]{2}')  => []  [6] pry(main)> User.where("'full_name' REGEXP ?", '[[:blank:]]{2}')  => []  [7] pry(main)> User.where("'full_name' RLIKE ?", '[[:blank:]]{2}')  => []  [8] pry(main)> User.where("'full_name' RLIKE ?", '[[:blank:]]{2}').to_sql  => "SELECT `users`.* FROM `users` WHERE ('full_name' RLIKE '[[:blank:]]{2}')"  [9] pry(main)> User.where("'full_name' RLIKE ?", '[[:blank:]]').count  => 0  [10] pry(main)> User.where("'full_name' RLIKE ?", '[[:space:]]').count  => 0  [11] pry(main)> User.where("'full_name' RLIKE ?", '.*[[:space:]].*').count  => 0  [12] pry(main)> User.where("'full_name' RLIKE ?", '\[[:space:]\]').count  => 0  

How to ensure Capistrano installs local gems on production

Posted: 19 Mar 2016 06:53 AM PDT

After running a successful cap production deploy, my app isn't getting the gems installed by Capistrano in the right location.

I would expect the gems to be installed here:

/home/user/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/

But instead, they're being installed here:

/home/y/app/shared/bundle/ruby/2.3.0/gems/

Furthermore, when running the command gem list, listing local gems, the results is very small (considering it should list more like 30 gems):

*** LOCAL GEMS ***    bigdecimal (1.2.8)  bundler (1.11.2)  io-console (0.4.5)  json (1.8.3)  psych (2.0.17)  rdoc (4.2.1)  

I realize this information is very little considering - let me know if there's any other information I can provide.

Restrict access in Rails app only for users logged in

Posted: 19 Mar 2016 07:00 AM PDT

I'm learning Rails and I'm trying to restrict access to pages if a user hasn't logged in and to only allow them to view the login and sign up pages.

Currently, my code creates a session when a user logs in and clears it when the user logs out. I've got a Sessions helper so that I can check whether a user is logged in but I'm unsure how to redirect the user throughout the app if he/she's not logged in.

CODE:

/controllers/application_controller.rb

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception    include SessionsHelper  end  

/controllers/sessions_controller.rb

class SessionsController < ApplicationController      def new    end      def create      user = User.find_by(email: params[:session][:email].downcase)      if user && user.authenticate(params[:session][:password])        log_in user        redirect_to user      else        flash.now[:danger] = 'Invalid email/password combination'        render 'new'      end    end      def destroy      log_out      redirect_to root_url    end    end  

/helpers/sessions_helper.rb

module SessionsHelper      # Logs in the given user.    def log_in(user)      session[:user_id] = user.id    end      # Returns the current logged-in user (if any).    def current_user      @current_user ||= User.find_by(id: session[:user_id])    end      # Returns true if the user is logged in, false otherwise.    def logged_in?      !current_user.nil?    end      # Logs out the current user.    def log_out      session.delete(:user_id)      @current_user = nil    end  end  

SystemStackError: Stack level too deep during Feature extraction using iron feature extraction

Posted: 19 Mar 2016 06:31 AM PDT

How to increase/solve problem with SystemStackError? I am trying to do something like:

x = '[User.where( :id => [1, 2, 3, 12800, 20542, 293416, 48688] ).includes(:personal_notifications, { :depots => [:positions, { :trades => { :instrument => [:instrument_markets, :prices, :translations] } }] }, :alerts, { :ratings => [{ :instrument => [:instrument_markets, :prices, :translations] }, :versions, :translations] } ), UserInfo.where( :user_id => [1, 2, 3, 12800, 20542, 293416, 48688] ), IndicesInstruments.all, Market.where( :id => 1..99 ).includes( :translations ), UserExperience.all, Campaign.all, Country.all, NewsCategory.all, GroupType.all, Site.all, Language.all, Currency.where( :id => 1..5 ).includes(:translations), CurrencyPair.all, Strategy.where(:id => 1..5).includes(:translations), ExternalNewsArticle.joins(:instrument_external_news_articles).where( :instrument_external_news_articles => {:instrument_id => [101, 1497]} ).includes( :instrument_external_news_articles ).order("external_news_articles.created_at DESC").limit(40), Price.where( :instrument_id => Instrument.where(:type => "Index")).includes( { :instrument => [:instrument_markets, :prices, :translations] } ), OpeningReason.where( :id => 1..7 ).includes( :translations ), NewsArticle.where( :author_id => [1, 2, 3, 12800, 20542, 48688] ).where("promoted_till is not null").order("promoted_till DESC").limit(100)]'  Fe.extract(x)  

It shows: SystemStackError: stack level too deep How can I solve this? I have tried by increasing stack by export RUBY_THREAD_VM_STACK_SIZE=2000000 but it didn't work

How to upload videos asynchronously using carrierwave

Posted: 19 Mar 2016 06:45 AM PDT

I'm using carrierwave to upload movies to amazon s3. I want to do it asynchronously so that I can upload multiple videos at the same time and I want to use a progress bar.

How can I do this?

Display checkbox instead of drop down select

Posted: 19 Mar 2016 06:42 AM PDT

I have the following form:

<%= form_for @user  do |f| %>     <div class="form-group">        <%= f.label :extra_act %>        <%= f.select(:extra_act, [['Act 1', 1],['Act 2', 2], ['Act 3', 3]], class: 'form-control', required: true)  %></br>     </div>  <%= f.submit 'Submit', class: 'btn btn-primary' %>  <% end %>  

Is there a way to offer checkboxes instead of the drop down select menu here? I have found checkboxes on the ruby website, but I only want users to have the option of selecting one checkbox.

How to parse variously formatted or natural language dates locally and pass to jquery datepicker?

Posted: 19 Mar 2016 05:44 AM PDT

I have a :date_as_text field in a Rails form. When the form is submitted this field is parsed by Chronic and a datetime saved to the database.

As this is a text field, the user can type a variety of different date formats, or even 'today', 'yesterday', etc and all (most) are interpreted by Chronic.

Input values can also be set via a jquery datepicker attached to the field.

If the user types an entry that corresponds exactly to the date format expected by datepicker (in this case yy-MM-dd), then the datepicker is updated to display the currently selected data.

How can I parse the entered value on the client side so that the datepicker will also recognize other date formats? I'm struggling to conceptualize how to even approach this.

  1. How to parse variously formatted or natural language dates locally? One approach seems to be https://github.com/datejs/Datejs, though this library does not appear to be well maintained.
  2. When to parse? x seconds after the last entry in the field? Or is there a better way?
  3. How to pass the parsed value into datepicker? Would the datepicker need to be reinitialized?

Does this sound feasible, or is a Really Bad Idea? Appreciate thoughts or experience from others.

`initialize': uninitialized constant ActionCable::Server::Configuration::ApplicationCable

Posted: 19 Mar 2016 06:27 AM PDT

I have upgraded my rails project from 4.x to 5.0.0.beta1 for use the actioncable and I have followed the example of DHH but it is not working. When I start the rails server it shows error:

$ rails s  => Booting Puma  => Rails 5.0.0.beta1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  Exiting    /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/configuration.rb:15:in `initialize': uninitialized constant ActionCable::Server::Configuration::ApplicationCable (NameError)    from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/base.rb:16:in `new'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/base.rb:16:in `block in <class:Base>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0.beta1/lib/active_support/core_ext/module/attribute_accessors.rb:72:in `block in mattr_reader'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0.beta1/lib/active_support/core_ext/module/attribute_accessors.rb:55:in `each'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0.beta1/lib/active_support/core_ext/module/attribute_accessors.rb:55:in `mattr_reader'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0.beta1/lib/active_support/core_ext/module/attribute_accessors.rb:208:in `mattr_accessor'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/base.rb:16:in `<class:Base>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/base.rb:12:in `<module:Server>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/base.rb:7:in `<module:ActionCable>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable/server/base.rb:6:in `<top (required)>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actioncable-5.0.0.beta1/lib/action_cable.rb:43:in `server'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config/routes.rb:28:in `block in <top (required)>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.beta1/lib/action_dispatch/routing/route_set.rb:380:in `instance_exec'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.beta1/lib/action_dispatch/routing/route_set.rb:380:in `eval_block'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.beta1/lib/action_dispatch/routing/route_set.rb:362:in `draw'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config/routes.rb:1:in `<top (required)>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:40:in `block in load_paths'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:40:in `each'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:40:in `load_paths'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:16:in `reload!'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:26:in `block in updater'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-5.0.0.beta1/lib/active_support/file_update_checker.rb:75:in `execute'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:27:in `updater'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/routes_reloader.rb:7:in `execute_if_updated'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application/finisher.rb:69:in `block in <module:Finisher>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/initializable.rb:30:in `instance_exec'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/initializable.rb:30:in `run'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/initializable.rb:55:in `block in run_initializers'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/initializable.rb:54:in `run_initializers'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/application.rb:350:in `initialize!'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config/environment.rb:5:in `<top (required)>'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config.ru:3:in `require'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config.ru:3:in `block in <main>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/builder.rb:55:in `instance_eval'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/builder.rb:55:in `initialize'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config.ru:in `new'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/config.ru:in `<main>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/builder.rb:49:in `eval'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/builder.rb:49:in `new_from_string'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/builder.rb:40:in `parse_file'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/server.rb:318:in `build_app_and_options_from_config'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/server.rb:218:in `app'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/server.rb:56:in `app'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-2.0.0.alpha/lib/rack/server.rb:353:in `wrapped_app'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/server.rb:134:in `log_to_stdout'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/server.rb:74:in `start'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/commands_tasks.rb:90:in `block in server'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/commands_tasks.rb:85:in `tap'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/commands_tasks.rb:85:in `server'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/command.rb:20:in `run'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.0.beta1/lib/rails/commands.rb:19:in `<top (required)>'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/bin/rails:8:in `require'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/bin/rails:8:in `<top (required)>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/lib/spring/client/rails.rb:27:in `load'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/lib/spring/client/rails.rb:27:in `call'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/lib/spring/client/command.rb:7:in `call'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/lib/spring/client.rb:26:in `run'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/bin/spring:48:in `<top (required)>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/lib/spring/binstub.rb:11:in `load'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.1.3/lib/spring/binstub.rb:11:in `<top (required)>'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /home/laport/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /home/laport/Téléchargements/Nouveau TP/Module_chat (copie)/bin/spring:16:in `<top (required)>'  from bin/rails:3:in `load'  from bin/rails:3:in `<main>'  

This is my Gemfile :

gem 'bcrypt'  gem 'faker'  gem 'carrierwave'  gem 'mini_magick'  gem 'fog'  # gem 'haml-rails'    gem 'sqlite3'    gem 'active_model_serializers', '~> 0.10.0.rc1'      gem 'sprockets'    gem 'sprockets-rails'    gem 'bourbon'    gem 'neat'    gem 'bitters'    gem 'bunny'      gem 'activesupport', '5.0.0.beta1'    gem 'actionpack'    gem 'arel'    gem 'rack'    gem 'puma', '2.15.3'    gem 'actioncable' , '5.0.0.beta1'        gem 'will_paginate'    gem 'bootstrap-will_paginate'    gem 'bootstrap-sass'    gem 'sass-rails'    gem 'uglifier'    gem 'coffee-rails'     gem 'jquery-rails'    gem 'turbolinks'     gem 'jbuilder'     gem 'sdoc'  

Unprocessable Entity uisng jquery ejax delete call

Posted: 19 Mar 2016 05:10 AM PDT

I've been facing issue of Unprocessable Entity.I am working on ruby on rails. When I send and ajax call to server my ajax code is

 $.ajax({          url: 'repository/destroyitems',          data:selected,          type: 'DELETE',          success: function(result) {      // Do something with the result      debugger;     }  

});

In controller I have simple actions

Rails don't render layout when create record with Ajax

Posted: 19 Mar 2016 05:12 AM PDT

My problem is after I create a new record with ajax I get a NOMETHODERROR and I must reload the page to see the new record.

The Error I get in terminal.

Rendered time_entries/_time_entry.html.erb (3.4ms) Rendered time_entries/create.js.erb (4.9ms) Completed 500 Internal Server Error in 41ms (ActiveRecord: 4.4ms)

NoMethodError - undefined method `each' for nil:NilClass:
app/views/time_entries/_time_entry.html.erb:1:in '_app_views_time_entries__time_entry_html_erb___4086905375499854267_70174828432680'

What I do wrong?

time_entries_controller.erb

class TimeEntriesController < ApplicationController      ...      respond_to :html, :js      def index      @time_entries = current_user.time_entries.all.order("date DESC")      @time_entries_days = @time_entries.group_by{ |t| t.date.beginning_of_day }      respond_with(@time_entry)    end      def create      @time_entry = TimeEntry.new(timeentry_params)      @time_entry.user_id = current_user.id        respond_to do |format|        if @time_entry.save          format.html { redirect_to @time_entry, notice: 'Arbeitszeit wurde eingetragen' }          format.json { render :show, status: :created, location: @time_entry }          format.js        else          format.html { render :new }          format.json { render json: @time_entry.errors, status: :unprocessable_entity }          format.js        end      end      end      ...  

_time_entry.html.erb
the partial

<% @time_entries_days.each do |day, time_entries| %>      <% if day.today? %>          <div class="column-12 list-group">Today, <%= l day, format: :dm %></div>      <% else %>          <div class="column-12 list-group"><%= l day, format: :dm %></div>      <% end %>        <ul class="lists">        <% time_entries.each do |time_entry| %>          <li class="list-item" id="time_entry_<%= time_entry.id %>">            <div class="list-item__content">              <h3 class="list-item__title">                <%= link_to time_entry.category.name, time_entry %>                <span><%= l time_entry.start_time, format: :hm %></span> - <span><%= l time_entry.end_time, format: :hm %></span>              </h3>              <p><%= time_entry.note %></p>            </div>            <span class="list-item__label"><%= time_entry.hours %>h</span>          </li>        <% end %>      </ul>  <% end %>  

index.html.erb

  <% if can? :create, TimeEntry %>        <%= link_to 'Add new Time Entry', new_time_entry_path, remote: true, class: 'btn btn-primary', :data => { :'popup-open' => 'popup-1' } %>    <% end %>      ...      <div class="row" id="container_time_entries">      <%= render "time_entry" %>    </div>  

create.js.erb for testing
I don't get an alert after I create a new time entry.

alert("HALLO");  

create.js.erb normal

$('.modal-bg').hide();  $('.popup').fadeOut(350);  $('#container_time_entries').html("<%= j(render 'time_entry') %>");  

cannot load such file -- tml (LoadError) in Rails 4.2.6

Posted: 19 Mar 2016 05:02 AM PDT

I am developing rails 4.2.6 application where used below gems

gem 'globalize', '~> 5.0.1'  gem 'tml-rails', '~> 5.4.1'  gem 'tml', '5.4.5'  

But i got below error when try to run project

   "NetworkError: 403 Forbidden - https://tools.translationexchange.com/tml/stable/tml.min.js"      TypeError: jade_mixins.language is not a function  

What is wrong here? any one have a idea?

Thanks

how to create users_controller.rb with devise?

Posted: 19 Mar 2016 04:37 AM PDT

I used gem: devise to create models/user.rb by running rails g devise User, and I used devise to create views by running rails g devise:views. Now I want to create controllers/users_controller.rb. How can I do that?

rails g controller users  

Is this correct? And is this user connected with devise User? I looked at another app, and class UsersController < ApplicationController works there.

I am new. Thanks for answering.

Unexpected trouble comparing numbers

Posted: 19 Mar 2016 06:17 AM PDT

I'm writing a helper method that adds a class to an element depending on whether two numbers are equal to eachother. My code is as follows:

<% for note in @company.convertible_notes.each %>      <% if note.id %>          <li class="tab <%= note_nav(params, note.id) %>"><%= link_to "#{note.security_series} #{note.security_class} Note", convertible_note_convertible_notees_path(note) %></li>      <% end %>  <% end %>  

note_nav calls the following helper:

def note_nav(params, note)      "active" if params[:controller]=="convertible_notees" && note.to_s==params[:converible_note_id].to_s  end  

Now the surprising thing is that I cannot get the expression note.to_s==params[:converible_note_id].to_s to register true. Even when I know the two numbers being compared are both "1". I checked it using my log:

logger.debug "are they equal? #{note.to_s==params[:converible_note_id].to_s} note.id is #{note} note params are #{params[:convertible_note_id]}"  

Which yields the following log entry:

are they equal? false note.id is 1 note params are 1

I would guess that they're two different types but given that I've converted both of them to_s, I don't know how that would be an issue. I've used this exact same technique on a few combinations of other models and have been completely error free. Any idea as to what might be going on?

Thanks in advance

How to print the Model.create calls made by FactoryGirl.create?

Posted: 19 Mar 2016 05:08 AM PDT

Is there any way to print the ActiveRecord operations called by FactoryGirl.create?

Say we have a factory :foo of model Foo. Running FactoryGirl.create(:foo), creates a database entry for the model Foo and some other entries for different models, say Bar, Car, etc.

Is there any way in which we could convert this FactoryGirl.create(:foo) command into its underlying Model.create commands?

For example

FactoryGirl.create(:foo)  

should break into

Foo.create(name: 'some name', ...)  Bar.create(field_value: 'asdf', ....)  Car.create(field_value: 'asdf1231', ....)  ...  

NOKOGIRI - Get all the elements that contain a dollar sign

Posted: 19 Mar 2016 06:27 AM PDT

Im trying to get the price generically from all the shopping sites

What i tried so far :

            price = doc.xpath('//span[contains(text(), "$")]').try(:first).try(:content)                if (!price)                  price = doc.xpath('//div[contains(text(), "$")]').try(:first).try(:content)              end  

Example of the html i tried : https://jet.com/product/adidas-Real-Madrid-Ball-15-5/a08713c229924ceca7171850680d3e32 (The HTML of this url)

this is not working so well, what am i doing wrong? Thanks you all

What happens when multiple processes try to write the same file?

Posted: 19 Mar 2016 05:56 AM PDT

Due to a limitation of a 3rd party library, I need to use a file with a static name. What happens in Rails if multiple users are trying to write to that file at the same time? EACCESS error?

Is there a way I could circumvent this?

What is the difference between index.html and index.html.erb in Rails?

Posted: 19 Mar 2016 03:04 AM PDT

I am trying to look up the index.html file in the 'public' directory but it doesn't appear there.

I only find index.html.erb in 'Posts' directory.

My route.rb says the following:

resources :posts
root 'posts#index'

How to show controller or model with all decorators applied from gems?

Posted: 19 Mar 2016 01:48 AM PDT

Is there a way to show the complete decorated controller/model in one file? For example, I have a controller that is being decorated with many gems I've installed and I would like to see the complete finished code in one view.

Bootstrap navigation tabs with rails subpages

Posted: 19 Mar 2016 03:08 AM PDT

I'm attempting to style a rails app with bootstrap navigation tabs. My App is such that I have not only pages but subpages as well. Tabs represent superpages (so to speak). See below:

<ul class="nav nav-tabs">      <li class="tab"><%= link_to "Contacts", edit_entities_path(@company) %></li>      <% for stock in @company.stocks.each %>          <% if stock.id %>              <li class="tab"><%= link_to "#{stock.security_series} #{stock.security_class} Stock", stock_stockholders_path(stock) %></li>          <% end %>      <% end %>      <% for option in @company.options.each %>          <% if option.id %>              <li class="tab"><%= link_to "#{option.security_series} #{option.security_class} Options", option_optionees_path(option) %></li>          <% end %>      <% end %>      <% for warrant in @company.warrants.each %>          <% if warrant.id %>              <li class="tab"><%= link_to "#{warrant.security_series} #{warrant.security_class} Warrant", warrant_warrantees_path(warrant) %></li>          <% end %>      <% end %>      <% for note in @company.convertible_notes.each %>          <% if note.id %>              <li class="tab"><%= link_to "#{note.security_series} #{note.security_class} Note", convertible_note_convertible_notees_path(note) %></li>          <% end %>      <% end %>  </ul>  

Tabs denote any number of stocks, convertible_notes, options, and warrants

resources :stocks do      resources :stockholders  end  resources :convertible_notes do      resources :convertible_notees  end      resources :options do      resources :optionees  end    resources :warrants do      resources :warrantees  end  

For more context a Company has_many :stocks :convertible_notes :options :warrants

What I'm after: I would like to apply the active class if I am on a given page OR if I'm on its sub-page. So, I not only want the stock with ID 1's tab to be .active if I'm on it, but also if I'm on the stockholder subpage.

What might be the best way to accomplish this? Thanks in advance.

SQL query for Rails 4 table reading one column but not the other correctly using .where

Posted: 19 Mar 2016 01:21 AM PDT

I need to produce a result based on an if condition that uses the && construction.

In my view, I need to do two things: 1) check to see if the current # of registered players exceeds the max specified by max_players; 2) Check and confirm that the user has not already registered.

If the query matches both conditions, I will return an error.

<% if Participation.where(game_id: params[:id]).count >= Game.first.max_players && Participation.where(user_id: current_user.id).exists?(false) %>   <p>Sorry, it failed.</p>    <% else %>    <div class="button-wrap">              <br>              <a class="btn rad-button2 wwt flat vertical" <%= link_to "Reserve Spot", reservation_path(id: params[:id]) %> </a>                </div>          <% end %>   

Despite how both conditions are structured almost identically, the 2nd condition seems to be "true" (meaning, weirdly in this case, that it is false, and the current_user.id does not exist) at all times regardless of what is in the real table.

Testing

  1. First thing I checked was to identify which condition was causing a problem. If I remove the 2nd condition and go to a game where the # of matching results with the same game_id in the table matches the params, it will show the error. So far, so good. However, if I use the second condition only on a game where the current_user has registered, it still defaults to the else condition.

  2. Am I sure there are results that match both conditions? Let's say I am using the URL http://localhost:3000/lobby?id=2. Ok, I want to find matching results with the id of "4."

    Participation id: 4, user_id: 2, game_id: 2, ranking: 0, created_at: "2016-03-19 07:20:14", updated_at: "2016-03-19 07:20:14">,   Participation id: 30, user_id: 3, game_id: 2, ranking: 0, created_at: "2016-03-19 07:57:36", updated_at: "2016-03-19 07:57:36  

As you can see, we have two game_id for our matching params. In my Game table, I specify that the max is 1 player for testing, so 2 > 1, and first condition passes (and the test with it alone is successful at producing error).

The second condition though -- when signed in as user_id: 2 still fails to produce the error, yet it is using the same where strategy.

Any idea where I am going wrong?

Edit 1 - Adding Participation Migration

class CreateParticipations < ActiveRecord::Migration    def change      create_table :participations do |t|        t.references :user, index: true        t.references :game, index: true        t.integer :ranking, null: false, default: 0          t.timestamps       end      end     end  

How to return the validation values for a Rails model

Posted: 19 Mar 2016 01:29 AM PDT

Given a model validation such as

validates :my_number,     numericality: {       greater_than_or_equal_to: 1,      less_than_or_equal_to: 300    }  

How can I read and e.g. display these values in the view?

MyModel.validators_on(:my_number).first.options[:on_or_before]  

appears to be getting close. But this returns a file line reference, and I'm unsure how to manipulate this to return a value.

#<Proc:0x007fa5a3d3eb90@/Path/To/Project/app/models/my_model.rb:128 (lambda)>  

Is there a convenient way of accessing these validation values and doing something in the view like

<p>This value must be between <%= @model.my_number.validation_greater_than %> and <%= @model.my_number.validation_less_than %></p>  

Load Engine Views in Host App

Posted: 19 Mar 2016 12:51 AM PDT

To reduce repetition I put a very simple bootstrap validation system in a gem.

Along with helpers (already loading) I have 2 partials.
/app/views/notifiengine/_notfications.html.erb
/app/views/notifiengine/_validations.html.erb

In the past I would just generate the views, but this time I want to let the gem hold the partial and render it without copying the views over.

<%= render 'notifiengine/notifications' %>  

From my understanding rails looks in the apps/views/ which I tried than I also tried app/views/notifiengine with no difference says missing template. Am I missing a step somewhere or something?

GitLab archive over API creating endless zips inside zips

Posted: 19 Mar 2016 12:49 AM PDT

I am using the GitLab API to create repository archives and when I do it creates a zip file that has a zip inside, that has a zip inside, etc.

Here is the code that is making the request:

def self.get_archive(project_id, branch)      request = Typhoeus::Request.new(          BASE_URL + "/projects/#{project_id}/repository/archive?sha=#{branch}",          method: :get,          params: nil,          headers: {              "PRIVATE-TOKEN": ADMIN_TOKEN          }      )        request.run        response = request.response        if response.success?          file_name = "archive-#{SecureRandom.hex(5)}.zip"            File.open(Rails.root + "public/archives/" + file_name, "wb") do |file|              file.write(response.body)          end            return {              success: true,              file_path: "/archives/" + file_name          }      else          return {              success: false,              response_raw: response          }      end  end  

Any thoughts as to what's gone wrong? My thinking here was to take the binary that I get back and write it to a zip file.

Rails Order by SQL

Posted: 19 Mar 2016 01:13 AM PDT

I have a TraitQuestion model that have a number of traits or answers - each of which has a value such as 1, 2, 3, or -3105 (for none of the above). I can't change these values because they are required for an external API.

I'd like to order them by the value, but when I do that, the answer with -3105 shows up at the top even though it says "None of the above":

Answer 4 = -3105  Answer 1 = 1  Answer 2 = 2  Answer 3 = 3  

Any idea on how we could order this so that it's

1  2  3  -3105?  

I'm pretty new to SQL but it seems like I should be able to do something like this:

@trait_question.traits.order('CASE WHEN value AS int > 0 then 1 ELSE 0 END')  

But that doesn't work. Any ideas how I can adjust the order call SQL such that it would order them in the correct order?

EDIT: This is Postgresql 9.4.1 via Amazon AWS

Chain scopes between models in Rails

Posted: 19 Mar 2016 12:54 AM PDT

I'm having some trouble querying between models in Rails. I have a class Message that belongs_to: booking. My goal is to add an active scope to Message that depends on a Booking scope.

class Booking < ActiveRecord::Base    has_one :event    has_many :messages      def self.active      includes(:event).        where('events.endtime >= ? AND status IS NOT ?'              Time.current.beginning_of_week,                          statuses['canceled'])    end  end    class Message < ActiveRecord::Base    belongs_to :booking    belongs_to :person      self.active(person_id)      where(person_id: person_id).merge(Booking.active)    end  end  

I want to find the Messages directed to a specific Person where the associated Booking is active. I therefore wish to use the Booking.active when creating Message.active.

Calling Message.active(1) with above implementation returns the following error:

Association named 'event' was not found on Message; perhaps you misspelled it?

Is there any way I can use Booking.active in the implementation of Message.active and get Messages returned?

Active record query for finding products in each city

Posted: 19 Mar 2016 12:26 AM PDT

I have two models as given below. Address table has an attribute city. Is it possible to find out total no. of products in each city using active record queries or do can it be done only through native sql query?

    class Product < ActiveRecord::Base        has_one :address      end        class Address < ActiveRecord::Base        has_many :products      end  

Overriding association in ActiveModel Serializer - returns all attributes instead of serialized object attributes

Posted: 19 Mar 2016 12:16 AM PDT

I have 2 models : Repository and Branch, both of which have a corresponding serializer.

In RepositorySerializer, I want to list one default branch. Here's how I'm doing it:

attributes :id, :name, :ssh_url, :default_branch  has_many :branches    def default_branch    object.branches.find_by_name(object.default_branch)  end  

In BranchSerializer, I have:

attributes :id, :name  

branches returns all branches properly serialized and only containing id and name attribute, but default_branch returns all the attributes of that branch.

Is there any way to utilize the existing BranchSerializer in this case or should I myself return the required attributes from the method default_branch.

Any help would be appreciated.

override concept is not working with Rails4 [on hold]

Posted: 18 Mar 2016 11:44 PM PDT

In Rails4 I created a plugin and I am trying to override core code controllers and views using instance_eval. But it's not overrided.

stripeToken is not being returned to my form

Posted: 18 Mar 2016 11:02 PM PDT

I have my Stripe integration setup correctly, because it does return an error This customer has no attached payment source which is a Stripe error indicating that the form is not returning sufficient payment info.

This is my subscriptions.js.coffee:

stripeResponseHandler = (status, response) ->    $form = $('#payment-form')    if response.error      #Show the errors on the form      $form.find('.payment-errors').text response.error.message      $form.find('button').prop 'disabled', false    else      # response contains id and card, which contains additional card details      token = response.id      #Insert the token into the form so it gets submitted to the server      $form.append $('<input type="hidden" name="stripeToken" />').val(token)      # and submit      $form.get(0).submit()    return    jQuery ($) ->    $('payment-form').submit (event) ->      $form = $(this)      $form.find('button').attr 'disabled', true      Stripe.card.createToken $form, stripeResponseHandler      false    return  

This is my form at new.html.erb:

<% unless @subscription.errors.blank? %>    <%= @subscription.errors.full_messages.to_sentence %>  <% end %>    <h2>Subcribing to <%= @plan.name %></h2>    <%= form_for @subscription, html: {id: 'payment-form'} do |f| %>    <input type="hidden" name="plan_id", value="<%= @plan.id %>" />    <span class="payment-errors"></span>      <div class="form-row">      <label>        <span>Email Address</span>        <input type="email" size="20" name="email_address" />      </label>    </div>      <div class="form-row">      <label>        <span>Card Number</span>        <input type="text" size="20" data-stripe="number" />      </label>    </div>      <div class="form-row">      <label>        <span>CVC</span>        <input type="text" size="4" data-stripe="cvc" />      </label>    </div>      <div class="form-row">      <label>        <span>Expiration (MM/YYYY)</span>        <input type="text" size="2" data-stripe="exp-month" />      </label>      <span> / </span>      <input type="text" size="4" data-stripe="exp-year" />    </div>      <button type="submit">Pay Now</button>  <% end %>  

This is the SubscriptionsController#Create:

  def create      @plan = Plan.find(params[:plan_id])      @subscription = CreateSubscription.call(        @plan,        params[:email_address],        params[:stripeToken]      )      if @subscription.errors.blank?        flash[:notice] = "Thank you for your purchase! Please click the link in the email we just sent you to get started."        redirect_to authenticated_root_path      else        render :new      end    end  

The above calls this app/services/create_subscription.rb:

class CreateSubscription    def self.call(plan, email_address, token)      user, raw_token = CreateUser.call(email_address)        subscription = Subscription.new(        plan: plan,        user: user      )        begin        stripe_sub = nil        if user.stripe_customer_id.blank?          binding.pry          customer = Stripe::Customer.create(            source: token,            email: user.email,            plan: plan.stripe_id          )            user.stripe_customer_id = customer.id          user.save!          stripe_sub = customer.subscriptions.first        else          customer = Stripe::Customer.retrieve(user.stripe_customer_id)          stripe_sub = customer.subscriptions.create(            plan: plan.stripe_id          )        end          subscription.stripe_id = stripe_sub.id          subscription.save!      rescue Stripe::StripeError => e        subscription.errors[:base] << e.message      end        subscription    end  end  

The reason I know that the form is not receiving the stripeToken is because when I use binding.pry in that create and did this:

00:52:31 web.1              |     14: def create  00:52:31 web.1              |     15:   @plan = Plan.find(params[:plan_id])  00:52:31 web.1              |  => 16:   binding.pry  00:52:31 web.1              |     17:   @subscription = CreateSubscription.call(  00:52:31 web.1              |     18:     @plan,  00:52:31 web.1              |     19:     params[:email_address],  00:52:31 web.1              |     20:     params[:stripeToken]  00:52:31 web.1              |     21:   )  00:52:31 web.1              |     22:   if @subscription.errors.blank?  00:52:31 web.1              |     23:     flash[:notice] = "Thank you for your purchase! Please click the link in the email we just sent you to get started."  00:52:31 web.1              |     24:     redirect_to authenticated_root_path  00:52:31 web.1              |     25:   else  00:52:31 web.1              |     26:     render :new  00:52:31 web.1              |     27:   end  00:52:31 web.1              |     28: end  00:52:31 web.1              |   [1] pry(#<SubscriptionsController>)> params  00:52:37 web.1              | => {"utf8"=>"✓", "plan_id"=>"1", "email_address"=>"someuser@test.com", "action"=>"create", "controller"=>"subscriptions"}  

Notice that there is no params[:stripeToken].

Also, when I try the binding.pry in my create_subscription.rb service, this is what I get:

00:52:41 web.1              |     10:     begin  00:52:41 web.1              |     11:       stripe_sub = nil  00:52:41 web.1              |     12:       if user.stripe_customer_id.blank?  00:52:41 web.1              |  => 13:         binding.pry  00:52:41 web.1              |     14:         customer = Stripe::Customer.create(  00:52:41 web.1              |     15:           source: token,  00:52:41 web.1              |     16:           email: user.email,  00:52:41 web.1              |     17:           plan: plan.stripe_id  00:52:41 web.1              |     18:         )  00:52:41 web.1              |   [1] pry(CreateSubscription)> token  00:52:44 web.1              | => nil  

What could be causing this and how do I fix it?

No comments:

Post a Comment