Monday, May 30, 2016

Ajax request not work rails 4 | Fixed issues

Ajax request not work rails 4 | Fixed issues


Ajax request not work rails 4

Posted: 30 May 2016 06:39 AM PDT

I am trying to hit the db at the exit of a field without reload the form using Ajax. The controller must do some process on the data obtained from the db and respond to the view. Then the user will continue with the input.

The following code is not working in my rails 4 app. I am missing something and just can't see what is wrong. I have the same piece of code working in a rails 3.2 application without problem.

In rails 3.2 the request go to check_matricula method, but in rails 4 go to show method in the controller.

Gemfile...

gem 'responders', '~> 2.0'

View...

<div class="field">      <%= f.text_field :matricula, { "data-remote" => true, "data-url" => "/liquidaciones_de_viajes/check_matricula", "data-type" => :json, :size => 10 } %>      <span id="check_matricula">&nbsp;</span>  </div>  

Controller...

class LiquidacionesDeViajesController < ApplicationController respond_to :html, :json

def check_matricula        @matricula = Matricula.find_by_codigo(params[:liquidacion_de_viajes][:matricula])      ... some process that result in matricula_ok true or false ...          if matricula_ok            respond_with(@matricula.empresa.razon_social)        else            respond_with(nil)        end    end  

assets/javascripts/check_matricula.js

$(document).ready(function() {      $("#liquidacion_de_viajes_matricula").bind('ajax:success', function(evt, data, status, xhr){          if (data !== null) {              $('#razon_social').html(data.razon_social);              $('#check_matricula').html('');          } else {              $('#check_matricula').html('Error de matricula');              $('#razon_social').empty();          }      });  $("#liquidacion_de_viajes_matricula").live('ajax:before', function(){      if ($(this).val() == '') {          return false;      }  });         $("#liquidacion_de_viajes_matricula").focus(function(){        $('#check_matricula').empty();        $('#razon_social').empty();    });    });  

ng token auth with rails devise user registration unpermitted parameters error

Posted: 30 May 2016 06:38 AM PDT

I have managed to set up ng-token-auth with ionic(angular) and devise-token-auth with rails however when I create a User an error is logged in the rails console even though the user is created.

In the console this shows up

Can't verify CSRF token authenticity  Unpermitted parameters: confirm_success_url, config_name, registration  Unpermitted parameters: confirm_success_url, config_name, registration  Unpermitted parameters: confirm_success_url, config_name, registration  

The user is created in the database however I have designed the ionic user controller to login the user once the registration is complete by using a promise. The controller is below:

comeDineApp.controller('userController', ['ipCookie','$scope', '$state', '$auth',  function(ipCookie, $scope, $state, $auth){      $scope.handleRegBtnClick = function() {      console.log("hello")      $auth.submitRegistration($scope.registrationForm)      .then(function() {        console.log("welcome")        $auth.submitLogin({          email: $scope.registrationForm.email,          password: $scope.registrationForm.password        });      });    };  }]);  

In this case the submitLogin function doesn't execute as the promise is not resolved even though the user is successfully created in the DB.

My rails user model is below:

class User < ActiveRecord::Base    # Include default devise modules.    devise :database_authenticatable, :registerable,    :recoverable, :rememberable, :trackable, :validatable,    :confirmable, :omniauthable    include DeviseTokenAuth::Concerns::User      has_many :tables        before_save -> do        self.uid = SecureRandom.uuid        skip_confirmation!      end    end  

and my user controller is:

class UsersController < ApplicationController      before_action :authenticate_user!    respond_to :json      def show      render json: current_user.tables    end  end  

Any ideas how I can resolve this either in the rails or the angular so that the error isn't presented and the angular promise resolves to login directly after signing up?

ruby on rails slim how to handle a value in select

Posted: 30 May 2016 06:27 AM PDT

I want to save the value of the option after submit .this a part of code (slim) but i can use also rubyon rails. please someone have any idea the select item is reference- brand- color- model- gender-ext_product_id

well.search-form  form  input type="hidden" value="put" name="_method"  - if search.scope == :my_items    input type="hidden" value="#{search_params.published}" name="published"    input type="hidden" value="#{search_params.query}" name="query"  fieldset    .row-fluid       .span8        label for="query" =translate"keyword"        select#query.selectoption name="keywordSearch"            option[value="reference" name="reference" selected=("selected" if @_source=="reference")] Reference           option[value="brand" name="brand" selected=("selected" if @_source=="brand")] Brand           option[value="model" name="model" selected=("selected" if @_source=="model")] Model           option[value="color" name="color"  selected=("selected" if @_source=="color")] Color           option[value="ext_product_id" name="ext_product_id" selected=("selected" if @_source=="ext_product_id")] Productid           option[value="gender" name="gender" selected=("selected" if @_source=="gender")] Gender  

Rescue exception thrown by a redirect_to :back

Posted: 30 May 2016 06:59 AM PDT

Little background information: I have a project with authenticated users which can have multiple 'scopes' of data. A scope determines which records can and can't be accessed by a user. A logged in user is always subsribed to a single scope stored in the session.

A user can at any time switch between the scopes he has access to, regardless of which page he is on.

After a scope switch I would like to try to reload the same page by using redirect_to :back. This is not always possible, since the current scope might not allow access to the page that was previously being viewed.

In those cases, the controller in question will throw an ActiveRecord::RecordNotFound exception in the respective controller on the .find(params[:id]) call, which is very ugly. I would very much like to gracefully fallback to a redirect_to :root with an accompanying alert message.

Currently I have this, but this does not work:

  def switch_scope      s = current_client.scopes.find(params[:scope_id])      set_scope(s.id)      begin        flash[:notice] = 'Scope switched succesfully.'        redirect_to :back # <= This might throw NotFoundException      rescue        flash[:alert] = 'Scope switched. Page could not be reloaded'        redirect_to :root      end    end  

Calculate NPS in Ruby

Posted: 30 May 2016 07:00 AM PDT

The net promoter score can have the values 0-10. It is divided in three groups:

Promoters = respondents giving a 9 or 10 score
Passives = respondents giving a 7 or 8 score
Detractors = respondents giving a 0 to 6 score

The score is calculated as the difference between the percentage of Promoters and Detractors.

Let's say we have the scores [10, 9, 10, 6, 2, 5, 10].

This would give the score +14 (57% - 43%).

I wish I could count occurrences of a range in an array, if that would be possible I would do

total_count = array.size  promoters = array.count(9..10)  passives = array.count(7..8)  detractors = array.count(0..6)    promoters_perc = promoters.to_f / total_count * 100  detractors_perc = detractors.to_f / total_count * 100    score = promoters_perc - detractors_perc  

How can I do this calculation?

Categories with Ancestry gem

Posted: 30 May 2016 06:21 AM PDT

I'm struggling a bit to wrap my head around the Ancestry gem. I'm trying to make categories which contain products.

I've got my current setup as follows:

  • Categories has the column ':ancestry, :string'
  • Categories model has the line 'has_ancestry'
  • Products model has nothing to do with Ancestry on it yet.

How do I go about actually putting products within certain categories? or is the set-up right for doing the following tree structure:

Category  - Product  - Product  - Product    Category  - Product  - Product  - Product  

Any help would be brilliant.

Active Model Serializers 0.10 exclude namespaces with JSON adapter?

Posted: 30 May 2016 06:36 AM PDT

Is there some way to exclude the namespace part of the model name in the root key?

I used Active Model Serializer version 0.9 before and my JSON representation of a User at localhost:3000/api/v1/users/1 was something like:

{ "user": { "id": 1, "first_name": "Foo", "last_name": "Bar" } }  

I recently upgraded to version 0.10 and now I get the namespace included in the root key:

{ "api/v1/user": { "id": 1,"first_name": "Foo", "last_name": "Bar" } }  

I want the root key to be like before, that is "user" instead of "api/v1/user".

web_1 | /docker-entrypoint.sh: line 99: exec: bundle: not found app_web_1 exited with code 127

Posted: 30 May 2016 05:50 AM PDT

I'm trying to use docker to push my existing rails project to a docker container.

I'm using postgres database.

When I did

docker-compose up

I get following error in the logs.

web_1  | /docker-entrypoint.sh: line 99: exec: bundle: not found  app_web_1 exited with code 127  

DokcerFile

FROM ruby:2.2.0  RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs  RUN mkdir /myapp  WORKDIR /myapp  ADD Gemfile /myapp/Gemfile  ADD Gemfile.lock /myapp/Gemfile.lock  RUN gem install bundler  RUN bundle install  ADD . /myapp    FROM postgres:9.4  #FROM library/postgres  ENV POSTGRES_USER my-user-name  ENV POSTGRES_PASSWORD ''  ENV POSTGRES_DB app-database-name  

docker-compose.yml

version: '2'  services:    db:      image: postgres    web:      build: .      command: bundle exec rails s -p 3000 -b '0.0.0.0'      volumes:        - .:/myapp      ports:        - "3000:3000"      depends_on:        - db  

What is `StringIO` in the context of RSpec testing (Ruby on Rails)?

Posted: 30 May 2016 06:55 AM PDT

What is StringIO in Ruby on Rails?

I'm trying to understand another SO answer that references StringIO, but its over my head.

I would suggest using StringIO for this and making sure your SUT accepts a stream to write to instead of a filename.

testIO = StringIO.new  sutObject.writeStuffTo testIO   testIO.string.should == "Hello, world!"  

Source: Rspec: how to test file operations and file content

Ruby-doc.org

Pseudo I/O on String object.

Source: http://ruby-doc.org/stdlib-1.9.3/libdoc/stringio/rdoc/StringIO.html)

Robots.thoughtbot

This is common in tests where we might inject a StringIO instead of reading an actual file from disk.

Source: https://robots.thoughtbot.com/io-in-ruby#stringio

My case:

File.open("data.dat", "wb") {|f| f.write(snapshot)}  

In my application I want to test the above, but I'm still confused how StringIO applies to implementing an RSpec test.

Could anyone with some experience in StringIO give some guidance?

Can't read data from hash using column(:) in rails

Posted: 30 May 2016 06:02 AM PDT

a = {"item"=>{"id"=>"34567", "name"=>"AAX item 1 Inventory23", "description"=>"AAX item 1 Inventory23", "unit_price"=>"2342", "item_type"=>"Inventory", "track_qty_on_hand"=>"true", "qty_on_hand"=>"50000", "inv_start_date"=>{"(3i)"=>"4", "(2i)"=>"5", "(1i)"=>"2016"}}, "company_id"=>"1", "item_type"=>"Inventory", "amount"=>"1232"}

Output:

a['item'] = {"id"=>"34567", "name"=>"AAX item 1 Inventory23", "description"=>"AAX item 1 Inventory23", "unit_price"=>"2342", "item_type"=>"Inventory", "track_qty_on_hand"=>"true", "qty_on_hand"=>"50000", "inv_start_date"=>{"(3i)"=>"4", "(2i)"=>"5", "(1i)"=>"2016"}}

a[:item] = nil

So, How to get data as a[:item]. What I have to change?

Rails server not starting in production mode

Posted: 30 May 2016 06:29 AM PDT

I want to start my rails server in production mode but it is exiting immediately.

rails server -e production  => Booting Thin  => Rails 4.1.4 application starting in production on http://0.0.0.0:3000  => Run `rails server -h` for more startup options  => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)  => Ctrl-C to shutdown server  Thin web server (v1.6.4 codename Gob Bluth)  Maximum connections set to 1024  Listening on 0.0.0.0:3000, CTRL+C to stop  Exiting  

Performance issues when upgrading from ruby 1.9.3 to ruby 2.2.2

Posted: 30 May 2016 05:45 AM PDT

We have finally upgraded our app from ruby ruby-1.9.3-p545 to ruby-2.2.2. We are currently running rails 3.2

We have now subsequently encountered a 50% drop in performance. I am pretty suprised by this and not to sure where to start debugging. If anybody has any suggestions or experienced this pain before some advice would be much appreciated.

Ho do I specify how ActiveSupport::JSON.encode handles nested hash integer keys

Posted: 30 May 2016 05:54 AM PDT

I'm not sure if this is a bug, or if I'm missing an option to specify how to handle integer keys of nested hashes when converting to JSON using rails ActiveSupport::JSON.encode. Example of the problem

$ rails console  [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.  Loading development environment (Rails 3.2.22.1)    Frame number: 0/5  [1] pry(main)> ActiveSupport::JSON.encode({outer: {1 => "a"}})  => "{\"outer\":{\"1\":\"a\"}}"  

As you can see, the inner hash key 1 has been converted to a string. I know there are various options to specify how to handle unknown classes/type and ActiveRecord specific things (like allowing joins with :include), but I would have thought that an integer as a 'native' type wouldn't require that sort of thing, and that nesting would be handled by default.

update join table has_many through with additional checkboxes

Posted: 30 May 2016 05:46 AM PDT

if i dont find solution here i have no idea where i should looking for...

I know there is right, easy solution for it...but something i just dont understand.

I have 3 models...

Scheme.rb

class Scheme < ActiveRecord::Base    has_many :projects    has_many :custom_issue_field_definitions, through: :scheme_custom_issue_field_definitions    has_many :scheme_custom_issue_field_definitions  end  

CustomIssueFieldDefinition.rb

class CustomIssueFieldDefinition < ActiveRecord::Base    has_many :schemes, through: :scheme_custom_issue_field_definitions    has_many :scheme_custom_issue_field_definitions    belongs_to :custom_issue_field  end  

SchemeCustomIssueFieldDefinition.rb

class SchemeCustomIssueFieldDefinition < ActiveRecord::Base    belongs_to :scheme    belongs_to :custom_issue_field_definition  end  

Join Model have 3 additional fields...with type: boolean.

enter image description here


I'd like to update scheme_custom_issue_field_definitions table. How controller and form should looks like?

Additional image: enter image description here

Update:

In console i can update it like this:

a = Scheme.first  b = CustomIssueFieldDefinition.first  c = a.scheme_custom_issue_field_defintitions.find_or_create_by(custom_issue_field_definition: b)  c.update_attributes(visible: 1, reportable: 0, required: 0)  

Next Update:

Now form looks like this (what is completely wrong):

<%= simple_form_for @scheme_new_custom_issue_field, url: configurations_scheme_path(@scheme), method: :put do |f| %>        <% @available_custom_issue_field_definitions.each do |custom_issue_field| %>          <tr>              <td><%= custom_issue_field.label %></td>              <td><%= f.input :visible, as: :boolean %></td>              <td><%= f.input :reportable, as: :boolean %></td>              <td><%= f.input :required, as: :boolean %></td>          </tr>        <% end %>        <%= f.button :submit, class: "btn btn-primary" %>      <% end %>   

and schemes_controller

def update      @scheme = Scheme.find(params[:id])      @scheme_new_custom_issue_field = @scheme.scheme_custom_issue_field_definitions.        find_or_create_by(scheme_id: @scheme, custom_issue_field_definition_id: params[:custom_issue_field_definition_id])      if @scheme_new_custom_issue_field.update_attributes(scheme_custom_issue_field_definition_params)        flash[:success] = "Scheme has been successfully updated"        redirect_to :back      else        render :edit      end    end  

How can I avoid the Post Processing in Paperclip

Posted: 30 May 2016 05:37 AM PDT

I use Paperclip for Document and Image Processing of both Tiff and PDF. So Tiff and PDF could be downloaded. Tiff should be converted to PDF and PDF should be left as it is. But when I download an PDF the Destination File has only one page. It seems like the Post Processing of Paperclip makes an automatic convert:

convert '/tmp/00c865a9d6c212a20cd851a448969f5520160530-4574-1yqdtq.pdf[0]' -auto-orient '/tmp/00c865a9d6c212a20cd851a448969f5520160530-4574-1yqdtq20160530-4574-8l8k7z.pdf'  

How can I avoid the Post Processing?

My Code:

has_mongoid_attached_file :document, styles: lambda { |a|    if a.instance.isTiff?    {      pdf: {        format: 'pdf',        processors: [:tiff_to_pdf]      }    }    else    {      pdf: {        format: 'pdf'      }    }  end  }  

Rails 4 - Devise :return_to previous url

Posted: 30 May 2016 05:45 AM PDT

In rails 4.2.4, I am using devise (3.5.6, 3.5.2, 3.2.4) gem. The scenario which should work for me is,

When user try to access user_profile_url(:anchor=>'section1') page from an email, it asks him to login, after login it leads to users_home_path. If he already logged in then it directly redirect to user_profile_url page(#section1).

How can I redirect to user_profile_url(:anchor=>'section1') as soon as session creates (clicked from email link)? I have tried to fix it by modifying after_sign_in_path_for(resource) method but it is not working.

def after_sign_in_path_for(resource)    session[:return_to] || users_home_path  end  

Please help me to solve this issue.

RoR: Cannot Migrate Database to Heroku

Posted: 30 May 2016 05:54 AM PDT

I am having trouble migrating my database to Heroku. I have checked the other issues that address this to no avail. I can really use a second pair of eyes on my code to help me figure this out.

This is the error I get:

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "props" does not exist  : ALTER TABLE "comments" ADD CONSTRAINT "fk_rails_1d3f70cf04"  FOREIGN KEY ("prop_id")    REFERENCES "props" ("id")  

enter image description here

It seems to get caught while migrating this file:

class CreateComments < ActiveRecord::Migration    def change      create_table :comments do |t|        t.string :commenter        t.text :body        t.references :prop, index: true, foreign_key: true          t.timestamps null: false      end    end  end  

This is the migration file where I create the table props:

class CreateProps < ActiveRecord::Migration    def change      create_table :props do |t|        t.string :title        t.text :text        t.references :user, index: true, foreign_key: true          t.timestamps null: false      end    end  end  

My schema is here:

ActiveRecord::Schema.define(version: 20160528205746) do      # These are extensions that must be enabled in order to support this database    enable_extension "plpgsql"      create_table "answers", force: :cascade do |t|      t.string   "choice"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "created_by"      t.integer  "user_id"      t.integer  "prop_id"    end      create_table "comments", force: :cascade do |t|      t.string   "commenter"      t.text     "body"      t.integer  "prop_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      add_index "comments", ["prop_id"], name: "index_comments_on_prop_id", using: :btree      create_table "props", force: :cascade do |t|      t.string   "title"      t.text     "text"      t.integer  "user_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "choice"      t.string   "answer"      t.integer  "answerId"    end      add_index "props", ["user_id"], name: "index_props_on_user_id", using: :btree      create_table "user_answers", force: :cascade do |t|      t.integer  "user_id"      t.integer  "answer_id"      t.datetime "created_at"      t.datetime "updated_at"    end      create_table "users", force: :cascade do |t|      t.string   "username"      t.string   "email"      t.integer  "score",           default: 0      t.integer  "prop_id"      t.datetime "created_at",                      null: false      t.datetime "updated_at",                      null: false      t.string   "password_digest"      t.string   "created_by"      t.boolean  "admin",           default: false      t.integer  "answers_id"      t.integer  "answer_id"    end      add_index "users", ["answer_id"], name: "index_users_on_answer_id", using: :btree    add_index "users", ["prop_id"], name: "index_users_on_prop_id", using: :btree      create_table "wins", force: :cascade do |t|      t.string   "correctAnswer"      t.integer  "user_id"      t.datetime "created_at",    null: false      t.datetime "updated_at",    null: false    end      add_index "wins", ["user_id"], name: "index_wins_on_user_id", using: :btree      add_foreign_key "users", "answers"  end  

localhost issue for Ruby on Rails Existing Project, On a new project everything works fine

Posted: 30 May 2016 05:15 AM PDT

Ruby on rails can't connect to localhost after the server starts normally by typing rails s on console - boots using thin ... - Hosts file is fine .. - Created a new project and everything works fine with it .. - can't connect to localhost on Existing project(xyz) , no errors in log file .. - Same project runs fine on my other laptop. - tried for 127.0.0.1 and other ports

$ ruby -v  ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin15]  rails -v  Rails 4.2.1      $ telnet localhost 3000  Trying ::1...  telnet: connect to address ::1: Connection refused  Trying 127.0.0.1...  telnet: connect to address 127.0.0.1: Connection refused  telnet: Unable to connect to remote host  --------------------  

what do i do ? please help. Thanx in advance.

There was an error while trying to load the gem 'yard'

Posted: 30 May 2016 05:06 AM PDT

I am using sidekiq upstart job but while running sudo service sidekiq restart getting the following error

There was an error while trying to load the gem 'yard'.  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'  /home/ubuntu/myapp/config/application.rb:8:in `<top (required)>'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/sidekiq-3.2.5/lib/sidekiq/cli.rb:231:in `require'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/sidekiq-3.2.5/lib/sidekiq/cli.rb:231:in `boot_system'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/sidekiq-3.2.5/lib/sidekiq/cli.rb:49:in `run'  /home/ubuntu/.rvm/gems/ruby-2.2.1@global/gems/sidekiq-3.2.5/bin/sidekiq:8:in `<top (required)>'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/bin/sidekiq:23:in `load'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/bin/sidekiq:23:in `<main>'  

Following is the upstart job

/etc/init/sidekiq.conf

# /etc/init/sidekiq.conf - Sidekiq config    # This example config should work with Ubuntu 12.04+.  It  # allows you to manage multiple Sidekiq instances with  # Upstart, Ubuntu's native service management tool.  #  # See workers.conf for how to manage all Sidekiq instances at once.  #  # Save this config as /etc/init/sidekiq.conf then manage sidekiq with:  #   sudo start sidekiq index=0  #   sudo stop sidekiq index=0  #   sudo status sidekiq index=0  #  # Hack Upstart's reload command to 'quiet' Sidekiq:  #  #   sudo reload sidekiq index=0  #  # or use the service command:  #   sudo service sidekiq {start,stop,restart,status}  #    description "Sidekiq Background Worker"    # This script is not meant to start on bootup, workers.conf  # will start all sidekiq instances explicitly when it starts.  start on runlevel [2345]  stop on runlevel [06]    # change to match your deployment user   setuid ubuntu   setgid ubuntu      #respawn  #respawn limit 3 30    # TERM is sent by sidekiqctl when stopping sidekiq. Without declaring these as  # normal exit codes, it just respawns.  normal exit 0 TERM    # Older versions of Upstart might not support the reload command and need  # this commented out.  reload signal USR1    # Upstart waits 5 seconds by default to kill the a process. Increase timeout to  # give sidekiq process enough time to exit.  kill timeout 15    #instance $index    script  # this script runs in /bin/sh by default  # respawn as bash so we can source in rbenv  exec /bin/bash <<'EOT'    # Pick your poison :) Or none if you're using a system wide installed Ruby.      source /home/ubuntu/.bash_profile    source /home/ubuntu/.rvm/scripts/rvm    source /home/ubuntu/.bashrc    # Logs out to /var/log/upstart/sidekiq.log by default      cd /home/ubuntu/myapp/    exec bundle exec sidekiq -C config/sidekiq.yml -e production  EOT  end script  

How to get this working. I had also installed the gem yard but still getting the same error.

What is the best way to do Natural Language Processing in Rails app?

Posted: 30 May 2016 05:56 AM PDT

I have a Rails app. I need to implement automatic text categorization algorithms and possibly more NLP capabilities in app. I believe Ruby does not have good NLP tools available as Python has. I am using a separate resque server for process background jobs. I believe I have following

  1. Run python scripts using resque jobs
  2. Run a flask application on a separate server which can either talk to resque job or can automatically update the app database with processed results.
  3. Use Ruby tools mentioned in this thread
  4. Any other suggestions welcome

Please let me know what is the best way to do it. Are there any similar working examples?

ruby on rails many to many relationship views

Posted: 30 May 2016 06:10 AM PDT

i have created a many to many relationship between my phones table and accessories table using:

class Accessory    has_and_belongs_to_many :phones  end    class Phone    has_and_belongs_to_many :accessories  end  

I also implemented an intermediate table with and combined index of these tables ID's.

i am attempting to display two accessories for each phone which i have added in my seeds file.

This is code for my show.html - accessories

<div class="container">  

<% @accessories.each_slice(3) do |accessory| %>    <div class="row" >      <% accessory.each do |accessory| %>        <div class="col-lg-4" align="center">              <div id="img-box" , title="select image for more details ..." >            <% if not accessory.img_url.blank? %>              <%= link_to (image_tag accessory.img_url,:size => "200x160" ,class:"img-thumbnail" ),accessory %>              <% else %>                <%= link_to (image_tag("noimage.jpg",:size => "100x125")),accessory %>            <% end %>          </div>                <br/>                Name: <%= accessory.name %>                    Price: <%=  number_to_currency accessory.price, unit: "£"  %><br/>                    <td><%= link_to 'Edit', edit_accessory_path(@accessory) %> |  <%= link_to 'Back', accessories_path %>                </td>            <% end %>          </div>        </div>      <% end %>      </div>  <% end %>    </div>  

but i get the error :

show.html.erb:37: syntax error, unexpected keyword_ensure, expecting end-of-input

When removing <% end %> from a line, i then get the error:

undefined method `each_slice' for nil:NilClass

i have a link from a phone to the related accessory but wish to display more than one.

Thank you for any help :)

Rails nested form - refactor create action | cocoon gem

Posted: 30 May 2016 05:41 AM PDT

Everything is working fine but I want to change the code in create action to something like in update action. Right now, in the create action I am looping through all the values and saving them, but want to do it in a single line.

I have a College model.

class College< ActiveRecord::Base     has_many :staffs, dependent: :destroy     accepts_nested_attributes_for :staffs, reject_if: :all_blank, allow_destroy: true  end  

And this is my Staff.rb

class Staff < ActiveRecord::Base    belongs_to :college  end  

And these are my Staffs controller create and update actions

def create    @college= College.find(params[:college][:id_college_profile]    )    staff_params = params[:college][:staffs_attributes].values    staff_params.each do |staff_param|      @staff = @college.staffs.new      @staff.name = staff_param[:name]      @staff.designation = staff_param[:designation]      @staff.experience = staff_param[:experience]      @staff.specialization = staff_param[:specialization]      @staff.save    end    redirect_to dashboard_path(id: @college.id), notice: "Successfully added Staff."  end    def update    @college= College.find(params[:college][:id_college]    )    @college.update_attributes(staff_parameters)    redirect_to root_path  end  

These are strong parameters

def staff_parameters    params.require(:college).permit(:id, staffs_attributes: [:id,  :name, :specialization, :experience, :designation, :_destroy])  end  

Is there a way to save all of staffs in create action, without looping through all the values, but save all of them with a single line of code as in update action?

I have tried this in the StaffsController create action

def create    @college= College.find(params[:college][:id_college]    )    @staff= @college.staffs.new(staff_parameters)    @staff.save      redirect_to dashboard_path(id: @college.id), notice: "Successfully added Staffs."  end  

But it threw this error

unknown attribute 'staffs_attributes' for Staff.  

Can someone kindly help me with this issue?

How to pass authentication token in RSpec test for JSON API?

Posted: 30 May 2016 04:07 AM PDT

I'm trying to add an authorization token to an RSpec get JSON API test in Rails. But everything tried so far results in an error. The issue seems that the token is not being properly passed in the request.

expected the response to have a success status code (2xx) but it was 401  

Current code:

Project_spec.rb (tests)

before do      @project = create(:project, :key => "123")      get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json  end    it "returns correct status" do      expect( response ).to have_http_status(:success)  end  

ProjectsController.rb

before_filter :restrict_access, :except => :create    def show      @project = Project.find(params[:id])      render json: @project  end    def restrict_access      authenticate_or_request_with_http_token do |token, options|          Project.exists?(key: token)      end  end  

Based on a few recommended solution found online, I've tried

  1. get '/api/v1/projects/1', format: :json, token: "123"

  2. get '/api/v1/projects/1', { 'HTTP-AUTHORIZATION' => 'Token "123"' }, format: :json

  3. get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json

But nothing seems to successfully pass the authorization token.

Note: Style in #3 works when posting from an external application, but not in the RSpec test itself.

Does anyone have experience with this and can share some direction?

Load Balancing - Web Applications with NGINX

Posted: 30 May 2016 04:51 AM PDT

I have a web application ruby on rails who is not configured to multithreading. In nginx config, I set up an upstream block to be load balanced. Like this :

upstream myapp {    server 127.0.0.1:3075;    server 127.0.0.1:3076;    server 127.0.0.1:3077;  }  

I set up also 3 process thin with 3 ports (3075,3076,3077).

I think when my first application '127.0.0.1:3075' is busy, all the request will be balanced automatically to my second application '127.0.0.1:3076' or the third one.

But load balancing is not work, even though my three web applications are running correctly independent.

Where is my problème ? thank you for your reponse.

------------------- nginx config --------------------

upstream myapp_hosts {      server  127.0.0.1:3075;      server  127.0.0.1:3076;      server  127.0.0.1:3077;  }    server {      listen       80;      server_name  myapp.mydomain.com;      rewrite ^(.*)$ http://myapp.mydomain.com$1 permanent;      access_log /var/log/nginx/myapp.access.log;        location / {              proxy_pass         http://myapp_hosts/;              proxy_connect_timeout   900;              proxy_send_timeout      900;              proxy_read_timeout      900;              proxy_buffer_size   16k;              proxy_buffers       32   16k;              proxy_busy_buffers_size 64k;      }      location /public {              root /var/www/nemo/;        }      location /images {              root /var/www/nemo/assets/;        }      location /javascripts {              root /var/www/nemo/assets/;        }      location /stylesheets {              root /var/www/nemo/assets/;        }       client_max_body_size    10m;     client_body_buffer_size 128k;     client_header_buffer_size 64k;  }  

Access rails helpers methods inside presenter

Posted: 30 May 2016 04:00 AM PDT

I'm working on rails application, One of view page has lot of complex code, So moved logic to presenters but the problem I'm facing is not able to access helper methods inside the presenter.

Could any one help me to solve this issue, gone through the some SOF questions but it is not 'very' specific.

Cant we use include helper in the presenter or moving helper method into the presenter. which is the best way to approach this problem.

Errors when Deploying Rails app from my mac to vps server with Capistrano and Unicorn

Posted: 30 May 2016 03:33 AM PDT

I'm trying to deploy my rails app to VPS server with Capistrano and Unicorn but when I run (/etc/init.d/unicorn_app_name_env start) I got the following error

(/etc/init.d/unicorn_app_name: INIT_CONF: parameter not set)

SSHKit::Runner::ExecuteError: Exception while executing as deploy@IP... /etc/init.d/unicorn_app_name: INIT_CONF: parameter not set

What I should to solve this problem?

confusion in ruby on rails

Posted: 30 May 2016 03:26 AM PDT

I'm new in ruby on rails.Encountered a line

<span id="searchTab" class="<%=yield(:search_tab_id)%>"><%=link_to "Search", search_items_path %></span>  

what the line is doing exactly.

I want to implement another tab here named "XYZ" what are the steps I should follow.

what all things I have to add in controllers,views,routes etc

How to boost the closest created_at field in Elasticsearch?

Posted: 30 May 2016 05:19 AM PDT

I want to sort my query results following some boost rules and in the same time i want them to be sorted as possible by creation date, if i add a created_at sort, it changes everything and my results are not relevant anymore. So i guess the only way to do that is to boost created_at field (the newest has the biggest bonus in calculating score for that boost) but i dont know how to implement it. This is my query:

query = {    "query" : {      "bool" : {        "must" : [          {            "range" : {              "deadline" : {                "gte" : "2016-05-30T11:39:10+02:00"              }            }          },          {            "terms" : {              "state" : [                "open"              ]            }          },          {            "query_string" : {              "query" : "chant",              "default_operator" : "AND",              "analyzer" : "search_francais",              "fields" : [                "title^6",                "description",                "brand",                "category_name"              ]            }          }        ]      }    },    "filter" : {      "and" : [        {          "geo_distance" : {            "distance" : "40km",            "location" : {              "lat" : 48.855736,              "lon" : 2.32927300000006            }          }        }      ]    },    "sort" : [      {        "_score" : "desc"      },      #{      #  "created_at" : "desc"   ==> i tried this but it doesnt change results      #}    ]  }  

Create Excel file in Ruby on Rails with Axlsx

Posted: 30 May 2016 02:58 AM PDT

I try to create Excel files with the gem "axlsx". But i work for the first time with this gem and i try one Test.

I make one link_to to an controller action. There is no Error, but i didnt find a complete excel file.

Link_to :

<%= link_to "Test", { :controller => :orders, :action => :invoices_generate }, { class: "btn btn-primary btn-lg", style: "width: 100%;", format: 'xlsx'} %>  

My Controller :

def invoices_generate          respond_to do |format|      format.xlsx    end   end  

invoices_generate.xlsx.axlsx :

if examples.include? :basic    wb.add_worksheet(:name => "Basic Worksheet") do |sheet|      sheet.add_row ["First Column", "Second", "Third"]      sheet.add_row [1, 2, 3]      sheet.add_row ['     preserving whitespace']    end  end  

rails submit with diffrent values [loop] in nested forms

Posted: 30 May 2016 03:31 AM PDT

I am trying to deal in form with 2 level nested resource. My parrent resource is supplier. I've done adding (building) new descedants (address) in new ad edit form. I've also done adding (building) descedant of descedant (contacts) in new form but I have problem with adding descedant of descedant (contacts) in edit form. In edit form I want to add submit button [Add contact] after each contact and when user click on this button go to update method and build new contact instance in proper address -I need send with [Add contact] submit param with address ID. I have no idea how to do it. I've try hidden field but it send last hidden fiel value from loop. It is any chance to send diffrent param with submit button?

I have 2 level nested resource. Supplier has descedant -> address Address has descedant -> contact

Models: Supplier:

has_many :supplier_addresses     has_many :addresses, :through => :supplier_addresses     accepts_nested_attributes_for :addresses,                               :allow_destroy => true,                              :reject_if     => :all_blank    

Address:

has_many :address_contacts     has_many :contacts, :through => :address_contacts     accepts_nested_attributes_for :contacts,                               :allow_destroy => true,                              :reject_if     => :all_blank  

Contact:

 has_many :address_contacts     has_many :addresses, :through => :address_contacts  

Suppliers_Controller:

 class SuppliersController < ApplicationController       before_action :set_supplier, only: [:show, :edit, :update, :destroy]       def index        if params[:search]          @suppliers = Supplier.paginate(page: params[:page], :per_page => 15).by_letter(params[:search])           else          @suppliers = Supplier.paginate(page: params[:page], :per_page => 15).order(:name)        end     end      # GET /currencies/new    def new      @supplier = Supplier.new      ad=@supplier.addresses.build      ad.contacts.build    end      def show    end      def edit      ad=@supplier.addresses.build      ad.contacts.build    end       # POST /currencies    # POST /currencies.json    def create      @supplier = Supplier.new(supplier_params)      if add_address?        @supplier.addresses.build        respond_to do |format|          format.html { render :new }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      elsif add_contact?        @supplier.addresses[params[:add_id].to_i].contacts.build        respond_to do |format|          format.html { render :new }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      else        respond_to do |format|          if @supplier.save            flash[:info] = 'Supplier was successfully created.'            format.html { redirect_to @supplier }            format.json { render :show, status: :created, location: @supplier }          else            format.html { render :new }            format.json { render json: @supplier.errors, status: :unprocessable_entity }          end        end      end    end      # PATCH/PUT /currencies/1    # PATCH/PUT /currencies/1.json    def update      if add_address?        @supplier.addresses.build        respond_to do |format|          format.html { render :edit }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      elsif add_contact?        @supplier.addresses[params[:add_id].to_i].contacts.build        respond_to do |format|          format.html { render :edit }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      else        respond_to do |format|          if @supplier.update(supplier_params)            flash[:info] = 'Supplier was successfully updated.'            format.html { redirect_to supplier_url }            format.json { render :show, status: :ok, location: @supplier }          else            format.html { render :edit }            format.json { render json: @supplier.errors, status: :unprocessable_entity }          end        end      end    end      # DELETE /currencies/1    # DELETE /currencies/1.json    def destroy      @supplier.destroy      respond_to do |format|        flash[:info] = 'Supplier was successfully deleted.'        format.html { redirect_to suppliers_url }        format.json { head :no_content }      end    end       private      # Use callbacks to share common setup or constraints between actions.      def set_supplier        @supplier = Supplier.find(params[:id])      end        #for new add      def add_address?        params[:commit] == "Add address"      end        #for new add      def add_contact?        params[:commit] == "Add contact"      end        # Never trust parameters from the scary internet, only allow the white list through.      def supplier_params        params.require(:supplier).permit(:name, :notes, :min_order, :pay_terms,                                          addresses_attributes: [:id, :name, :street1, :street2, :county, :city, :country, :post_code, :_destroy,                                         contacts_attributes:[:id, :name, :job_title, :tel_no, :fax_no, :mobile_no, :email, :invoice_email, :contact_notes, :_destroy]])      end    end  

Form:

<%= form_for(@supplier) do |f| %>          <%= f.label :name %>        <%= f.text_field :name %>      <%= f.fields_for :addresses do |address| %>        <%= address.label :street %>      <%= address.text_field :street %>        <%= address.fields_for :contacts do |contact| %>        <%= contact.label :job_title %>      <%= contact.text_field :job_title %>        <%end%>        <%=hidden_field_tag params[:add_id], address.index%>      <div class="row">        <div class="actions text-center">          <%= f.submit  "Add contact",:class => 'btn btn-sm btn-warning custom2' %>        </div>      </div>      <%end%>      <div class="row">        <div class="actions text-center">          <%= f.submit "Add address",:class => 'btn btn-sm btn-warning custom2' %>          <%= f.submit :class => 'btn btn-sm btn-success custom2' %>        </div>      </div>    <%end%>  

No comments:

Post a Comment