Sunday, March 13, 2016

How can allow_nil let a empty string pass the validation | Fixed issues

How can allow_nil let a empty string pass the validation | Fixed issues


How can allow_nil let a empty string pass the validation

Posted: 13 Mar 2016 07:51 AM PDT

I am reading Michael Hartl's Ruby On Rails Tutorial (3rd). In chapter 9, there's an example showing us how to update the user info. I got confused by the allow_nil attached here. I simplified the code as below:

class User < ActiveRecord::Base    ...    has_secure_password    validates :password, presence: true, length: { minimum: 6 }, allow_nil: true    ...  end    myuser=User.new(name: "Foo_bar",email: "test@example.com", password: "123456", password_confirmation: "123456")  myuser.save  myuser=User.find(myuser.id)  myuser.update_attributes(name: "Bar_Foo",email: "test@example.com", password: "", password_confirmation: "")  # It will succeed! But WHY?  

I understand the allow_nil: true skips the validation when the value being validated is nil. Nevertheless obviously, password: "" is not a nil value. How can allow_nil: true allows an empty string?

Lightbox not working with Rails, even when document on page load ready is in the codes

Posted: 13 Mar 2016 07:45 AM PDT

I'm using Lightbox with Rails.

I've did what everyone suggest on stackoverflow with the lightbox-plus-jquery.js file to stop the turbolinks. i.e.

var ready;  ready = function() {    <the downloaded codes>        };  $(document).ready(ready);  $(document).on('page:load', ready);  

But my image gallery is still not working, dont think my codes are wrong since all my other JS files works with the above codes?

My html codes:

   <a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-3.jpg" data-lightbox="example-set" data-title="Click the right half of the image to move forward."><img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-3.jpg" alt=""/></a>      <a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-4.jpg" data-lightbox="example-set" data-title="Or press the right arrow on your keyboard."><img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-4.jpg" alt="" /></a>      <a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg" data-lightbox="example-set" data-title="The next image in the set is preloaded as you're viewing."><img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-5.jpg" alt="" /></a>      <a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-6.jpg" data-lightbox="example-set" data-title="Click anywhere outside the image or the X to the right to close."><img class="example-image" src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-6.jpg" alt="" /></a>  

CSS code is the default one downloaded from site.

Anyone successfully used lightbox with rails before? Or could help me crack this case?

Thanks in advance.

Create project in Redmine and replicate in TestLink automatically

Posted: 13 Mar 2016 07:39 AM PDT

There is a clean and functional way to create a project in Redmine and even be replicated in TestLink?

Or maybe a way to create a job to read the table where the Redmine creates the project and replicate to the base TestLink?

Redmine is done in Ruby and Testlink in PHP.

Both are in the same database server and use MySql .

Rails: Select tag causing param missing error

Posted: 13 Mar 2016 07:10 AM PDT

I have an Order model associated with Order Statuses. In the edit view I have a form_for with order status options on a select tag. When the view is rendered I can see the current order status pre-selected in the select tag. If I change it and submit the form I get this error: ActionController::ParameterMissing in OrdersController#update When I replace the select tag with a text_field I can change the order status id and submit the form successfully. I tried adding this to the form: :method => :put but gives me a routing error.

I researched my problem but I can't get it to work. Links I've researched:

rails 4 form_for with f.select isn't passing correct params, getting `param is missing` error

http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

Rails ActionController::ParameterMissing in QuestionsController#update

Order Edit view:

<%= form_for(@order)  do |f| %>                <% if @order.errors.any? %>                  <div id="error_explanation">                    <h2><%= pluralize(@order.errors.count, "error") %> prohibited this contact from being saved:</h2>                      <ul>                    <% @order.errors.full_messages.each do |message| %>                      <li><%= message %></li>                    <% end %>                    </ul>                  </div>                <% end %>                <div class="form-group">                  <h3>Order Id <%= @order.id %> | <%= @order.uuid %></h3>                   <h3>Order Total: <%= number_to_currency(@order.total) %></h3>                </div>                <br>                <div class="form-group">                  <%= f.label :order_status_id %><br>                      <%= select_tag :order_status_id, options_from_collection_for_select(OrderStatus.all, :id, :name, @order.order_status.id),:class => "form-control" %>                     </div>                   <div class="actions">                  <%= f.submit "submit", :method => :put, :class => "btn btn-primary" %>                </div>              <% end %> <!-- Order details -->  

orders_controller.rb

  def edit      authorize! :read, @orders      @order = Order.find_by_uuid(params[:id])      @reservations = @order.reservations      end      def update      @order = Order.find_by_uuid(params[:id])      @order_status = @order.order_status_id      respond_to do |format|        if @order.update(order_params)          format.html { redirect_to @order, notice: 'Order was successfully updated.' }          format.json { render :show, status: :ok, location: @order }        else          format.html { render :edit }          format.json { render json: @order.errors, status: :unprocessable_entity }        end      end    end  def order_params     params.require(:order).permit(:subtotal, :tax, :total, :order_status_id, :uuid, :id, :shipping)    end  

order.rb belongs_to :order_status

order_status.rb has_many :orders

Error:

param is missing or the value is empty: order    Rails.root: C:/Users/Antonio/Desktop/RegiSportV01/regisports  Application Trace | Framework Trace | Full Trace    app/controllers/orders_controller.rb:114:in `order_params'  app/controllers/orders_controller.rb:86:in `block in update'  app/controllers/orders_controller.rb:85:in `update'    Request    Parameters:    {"utf8"=>"✓",   "_method"=>"patch",   "authenticity_token"=>"DhUNbbAz/VBLoRmLN8sKf4Oq/SEWJt38HlWMQW/w+zjM3CZ0Sml4Ulv+dzwYDdv1fMN42sjF+Y4BcMwc5+sRyg==",   "order_status_id"=>"2",   "commit"=>"submit",   "id"=>"ebce4e1c-d81c-4171-aafa-a9e23b392525"}  

ruby syntax error, unexpected ':', expecting keyword_then

Posted: 13 Mar 2016 07:17 AM PDT

I've recently updated ruby from 1.8.7.374 to 2.1.2p95 and I have a svn post-commit script which was working fine but now it fails.

changes=`#{svnlook} diff #{repo} -r #{rev}`  body << "<pre>"  changes.each do |top_line|  top_line.split("\n").each do |line|  color = case    when line =~ /^Modified: / || line =~ /^=+$/ || line =~ /^@@ /: 'gray'    when line =~ /^-/ 'red:'    when line =~ /^\+/ 'blue:'    else "black"    end    body << %Q{<font style="color:#{color}">#{CGI.escapeHTML(line)}</font>    <br/>\n}    end    end    body << "</pre>"  

Here's the errors I get:

    [root@dev hooks]# ruby -c post-commit  post-commit:66: syntax error, unexpected ':', expecting keyword_then or     ',' or ';' or '\n'  ...ne =~ /^=+$/ || line =~ /^@@ /: 'gray'  ...                               ^  post-commit:67: syntax error, unexpected keyword_when, expecting    keyword_end    when line =~ /^-/ 'red:'        ^  post-commit:67: syntax error, unexpected tSTRING_BEG, expecting     keyword_end        when line =~ /^-/ 'red:'                       ^  post-commit:68: syntax error, unexpected keyword_when, expecting     keyword_end        when line =~ /^\+/ 'blue:'        ^  post-commit:68: syntax error, unexpected tSTRING_BEG, expecting     keyword_end        when line =~ /^\+/ 'blue:'                        ^  post-commit:69: syntax error, unexpected keyword_else, expecting     keyword_end        else "black"        ^  post-commit:65: warning: assigned but unused variable - color  post-commit:18: warning: assigned but unused variable - saddress  post-commit:20: warning: assigned but unused variable - sendmail  post-commit:73: syntax error, unexpected keyword_end, expecting end-of-    input  

Any help in solving this is much appreciated.

Ruby - Permission denied - connect(2) when trying to establish a web connection

Posted: 13 Mar 2016 06:31 AM PDT

This issue is getting me crazy, especially as everything was working before.

Every time I try to establish a web connection, I end up with a Permission denied - connect(2) error, for example trying to launch bundler:

Errno::EACCES: Permission denied - connect(2) for "bundler.rubygems.org" port 443    C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/net/http.rb:879:in `initialize'  

Edit: to be clear the issue is not related to bundler, I get the same error message for the following code:

require 'net/http'  Net::HTTP.get('google.com', '/index.html')  

gives me:

C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/net/http.rb:879:in `initialize': Permission denied - connect(2) for "food2fork.com" port 80 (Errno::EACCES)  

Environment

    Bundler   1.11.2      Rubygems  2.4.5.1      Ruby      2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]      GEM_HOME  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0      GEM_PATH  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0;C:/Users/user_name/.gem/ruby/2.2.0      Git       2.7.2.windows.1  

Any help very welcomed.

Using form to update has_many through join table

Posted: 13 Mar 2016 05:08 AM PDT

I am short of implementation ideas for my rails project. at this point it seems impossible to implement in rails.

I am cloning a sort of accounting software into a web app using rails framework for small manufacturing companies to keep track of their products stock in their different distribution branches.

I have 3 different models: "Product", "Branch" & "Accumulator"

class Branch < ActiveRecord::Base  has_many :accumulators  has_many :products, :through => :accumulators    end    class Product < ActiveRecord::Base  has_many :accumulators  has_many :branches, :through => :accumulators      def self.search(search)     if search      where('name LIKE ?', "%#{search}%")    end  end    class Accumulator < ActiveRecord::Base  belongs_to :product  belongs_to :branch  end  

I am new to rails and after reading up on many to many associations I came across using collections to add products to a branch "@branch.products << Product.all"

Is there a possible way to use a form "number_field_tag" in the branch show view to add multiple of specific products into the join table?

eg I want to add 10 of (Product) called "garden eggs" to a (Branch) called "lagos branch" to the (Accumulator) join table using a form in Branches show view?

Find associated model of all objects in an array

Posted: 13 Mar 2016 07:27 AM PDT

Using Rails 4, I have the following:

class Driver < ActiveRecord::Base    has_and_belongs_to_many :cars, dependent: :destroy  end    class Car < ActiveRecord::Base    has_and_belongs_to_many :drivers  end  

I have a join table cars_drivers with car_id and patient_id.

I want to find drivers who are 30 years old and above (driver.age > 30), drives a Honda (car.brand = "Honda"), and sum the number of drivers found. How do I do that?

Specify font and text formatting when generating file with send_data

Posted: 13 Mar 2016 03:43 AM PDT

I am using send_data to let users download a .txt file.

def download    data = "My file content"    send_data data, :filename => "file.doc"  end  

I am trying to customize the output: how can I change the font/font-size and add formatting such as h1/h2/p ?

I tried to add HTML or Markdown but common editors (MS Word and others) don't use it.

In active-model-serializers, how to limit the associated objects returned from a has_many association?

Posted: 13 Mar 2016 03:58 AM PDT

So I have

    render json: Post.all         

This returns all my Posts and in my Post serializer I have

    class PostSerializer < ActiveModel::Serializer        has_many :comments      end          

I want the number of comments returned in the JSON to be limited to 5 and have a variable which tells if more comments are there. Is this possible?

Edit: I think I'll manage the more part with a new call. But can't figure out how to limit the comments in the serializer

How to create multiple records with FactoryGirl? Currently images are applied only to first record

Posted: 13 Mar 2016 03:14 AM PDT

I am getting strange behavior from a spec/ factory. What am I doing wrong?

# feature spec     feature 'avatars' do    let(:user1) { create :user_with_profile, role: 1 }    let(:user2) { create :user_with_profile, role: 2 }    let(:user3) { create :user_with_profile, role: 3 }    let(:user4) { create :user_with_profile, role: 4 }       scenario 'displays user avatars' do       expect(find("ul.users")).to_not have_selector "img.role1[title='#{user1.name}']"      expect(find("ul.users")).to_not have_selector "img.role2[title='#{user2.name}']"      expect(find("ul.users")).to_not have_selector "img.role3[title='#{user3.name}']"      expect(find("ul.users")).to_not have_selector "img.role4[title='#{user4.name}']"    end  end    # factory    FactoryGirl.define do    factory :user do      email { Faker::Internet.email }      password Faker::Internet.password(10, 20)      trait :name do        name Faker::Name.name      end      # images are handled with Carrierwave      trait :avatar do        avatar { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'images', 'test_image.jpg')) }      end      factory :user_with_profile, traits: [:name, :avatar]    end  end     # view  <ul class='users'>    <% Users.all.each do |user| %>      <%= content_tag :li, class: "user_#{user.id}" do %>        <%= link_to user_path(user), title: user.name do %>          <% if user.avatar? %>            <%= image_tag user.avatar_url(:large), title: user.name, class: "role#{user.role}" %>          <% else %>            <%= content_tag :div, class: "role#{user.role}" do %>              <%= user.initials %>            <% end %>          <% end %>        <% end %>      <% end %>    <% end %>  </ul>  

The test is failing:

Failure/Error: expect(find("ul.users")).to have_selector "img.role2[title='#{user2.name}']"  expected to find css "img.role2[title='Jakob John']" but there were no matches  

I thought it odd that user1 was passing whereas user 2 was failing, so I got rspec to save_and_open_page.

<ul class="users">    <li class="user_1">      <a title="Jakob Johnson" href="/users/1">        <img title="Jakob Johnson" class= 'role1' src="/avatars/users/1/large/0000000005_35594307d1.jpg">      </a>    </li>    <li class="user_2">      <a title="Jakob Johnson" href="/users/2">        <div class='role2'>JJ</div>      </a>    </li>    ## user3 and user4 also have divs not imgs  </ul>  

Exactly the same code and factory is used for each user, so:

  1. Why has FactoryGirl created user1 with an avatar, and the other users without?
  2. Why has FactoryGirl created all users with the same name?

Am I using FactoryGirl incorrectly? I can't work out what I'm doing wrong, and any advice appreciated.

Rails SSL issue

Posted: 13 Mar 2016 06:42 AM PDT

I have an valid SSL certificate for one of my domain (let's say example.org).

I added to my /etc/hosts:

127.0.0.1 localhost example.com  

and started an Rails app using the SSL certificate:

thin start -p 3000 --ssl --ssl-key-file /path/to/key --ssl-cert-file /path/to/cert  

When I visit https://example.com:3000 first time Mac OS X ask me few times to permit certificate (I guess) and I did it.

Now when I start the Rails app without SSL (just rails s) all works but I see an "Invalid request: Invalid HTTP format, parsing fails." message in console:

Started GET "/" for 127.0.0.1 at 2016-03-13 15:21:01 +0530    ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"  Processing by ApplicationController#index as HTML    Rendered application/index.html.slim within layouts/application (237.7ms)    Rendered application/_header.html.slim (9.0ms)  Completed 200 OK in 304ms (Views: 294.7ms | ActiveRecord: 0.0ms)  Invalid request: Invalid HTTP format, parsing fails.          /Users/user/.rvm/gems/ruby-2.2.4/gems/thin-1.6.4/lib/thin/request.rb:84:in `execute'          /Users/user/.rvm/gems/ruby-2.2.4/gems/thin-1.6.4/lib/thin/request.rb:84:in `parse'          /Users/user/.rvm/gems/ruby-2.2.4/gems/thin-1.6.4/lib/thin/connection.rb:39:in `receive_data'          /Users/user/.rvm/gems/ruby-2.2.4/gems/eventmachine-1.0.9.1/lib/eventmachine.rb:193:in `run_machine'          /Users/user/.rvm/gems/ruby-2.2.4/gems/eventmachine-1.0.9.1/lib/eventmachine.rb:193:in `run'  

After some investigation I found out that the message appears in Safari on GET request on 3000 port for this project only.

If I change port, open application via Chrome or Firefox, if I run another Rails app on 3000 port there is no error message.

I tried to clear Safari's cookie for localhost, I tried to run rake tmp:clear and rake tmp:sessions:clear but it doesn't help.

Does anyone know how can I fix it for Safari?

Updated

When I run the app with Webrick or Puma there is the error messages as well:

Started GET "/dashboard" for ::1 at 2016-03-13 15:54:56 +0530    ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"  Processing by DashboardController#index as HTML    User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]    Rendered application/index.html.slim within layouts/application (268.9ms)    Rendered application/_header.html.slim (9.1ms)  Completed 200 OK in 398ms (Views: 367.1ms | ActiveRecord: 0.5ms)  [2016-03-13 15:54:57] ERROR bad Request-Line `\x16\x03\x01\x00?\x01\x00\x00?\x03\x01V???z?*)?!??r}f\t??Net?\x00\x00(\x00??$?#?'.  [2016-03-13 15:54:57] ERROR bad Request-Line `\x16\x03\x01\x00?\x01\x00\x00?\x03\x01V??w??@'???Zp@?????w7??\a\b9\x00\x00(\x00??$?#?'.  

for Webrick and

Started GET "/dashboard" for ::1 at 2016-03-13 15:58:19 +0530    ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"  Processing by DashboardController#index as HTML    User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]    Rendered application/index.html.slim within layouts/application (264.0ms)    Rendered application/_header.html.slim (9.1ms)  Completed 200 OK in 448ms (Views: 414.0ms | ActiveRecord: 0.7ms)  2016-03-13 15:58:20 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>  2016-03-13 15:58:20 +0530: ENV: {"rack.version"=>[1, 3], "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>true, "rack.multiprocess"=>false, "rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"3.0.2", "GATEWAY_INTERFACE"=>"CGI/1.2"}  ---  2016-03-13 15:58:20 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>  2016-03-13 15:58:20 +0530: ENV: {"rack.version"=>[1, 3], "rack.errors"=>#<IO:<STDERR>>, "rack.multithread"=>true, "rack.multiprocess"=>false, "rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"", "SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"3.0.2", "GATEWAY_INTERFACE"=>"CGI/1.2"}  

for Puma

Updated

I guess here is related thread:

https://discussions.apple.com/thread/5884595?start=15&tstart=0

Load more user movies via AJAX in rails

Posted: 13 Mar 2016 04:47 AM PDT

I have a search movies application (Rails 4) and in 'my_movies' page I'm trying to show 2 user movies on page load and then after clicking a link 'Load More' other 2 ones.

Now I get 500 (Internal Server Error) with this code. I think I have problems in my controller. What I'm doing wrong?

models/user.rb

class User < ActiveRecord::Base    has_many :movies, dependent: :destroy  end  

models/movie.rb

class Movie < ActiveRecord::Base    belongs_to :user  end  

controllers/users_controller.rb

class UsersController < ApplicationController    before_action :authenticate_user!    after_action :verify_authorized      def my_movies      authorize :user, :my_movies?      if params[:id]        @user_movies = current_user.movies.where('id < ?', params[:id]).limit(2)      else        @user_movies = current_user.movies.limit(2)      end      respond_to do |format|        format.html        format.js      end    end  end  

views/users/my_movies.html.slim

.row    .small-12.columns.block.movies_container      = render 'users/user_movies'    .row    .small-12.columns.block.load_more_container      = image_tag 'spinner.svg', style: 'display: none;', class: 'loading_icon'      = link_to 'Load More', my_movies_user_path, class: 'load_more'  

views/users/_user_movies.html.slim

- @user_movies.each do |movie|    h2.user_movie data-id='#{movie.id}'      = link_to movie.title, movie_path(movie)  

views/users/_user_movies.js.slim

| $('.movies_container').append('  = escape_javascript(render(partial: 'users/user_movies'))  | ');  

js/user.coffee

# when the page is ready for manipulation  $(document).ready ->  # when the load more link is clicked    $('a.load_more').click (e) ->  # prevent the default click action      e.preventDefault()      # hide load more link      $('.load_more').hide()      # show the loading icon      $('.loading_icon').show()      # get the last id and save it in a variable 'last-id'      last_id = $('.user_movie').last().attr('data-id')      # make an ajax call passing along our last users movie id      $.ajax        type: 'GET'        url: $(this).attr('href')        data: id: last_id        dataType: 'script'        success: ->          # hide the loading icon          $('.loading_icon').hide()          # show our load more link          $('.load_more').show()          return      return    return  

Screenshot of the error:

enter image description here

UPD: After restarting Rails AJAX works fine, but I get doubled movies (the same are shown), instead of getting 2 others from database.

The error starts from here (2) and maybe here (1), because I sent user id's and not his last movie id.

enter image description here

Here is the console logs when the XHR starts:

enter image description here

How it can be fixed?

P.S. You can find this app here in GitHub, feature branch 'Loading more'.

Problems relating to installing Ruby

Posted: 13 Mar 2016 04:03 AM PDT

I used the below link to solve the problem. But got few other problems.

gem install json -v 1.7.3 gives 'Please update your PATH to include build tools'

`enter code here`C:\>ruby dk.rb init  [INFO] found RubyInstaller v2.2.4 at C:/Ruby22  

Initialization complete! Please review and modify the auto-generated 'config.yml' file to ensure it contains the root directories to all of the installed Rubies you want enhanced by the DevKit.

I don't know what changes I am supposed to make and how.

C:\>ruby dk.rb install  [INFO] Updating convenience notice gem override for 'C:/Ruby22'  [INFO] Installing 'C:/Ruby22/lib/ruby/site_ruby/devkit.rb'    C:\>gem install rdiscoun  t --platform=ruby  Fetching: rdiscount-2.1.8.gem (100%)  Temporarily enhancing PATH to include DevKit...  Building native extensions.  This could take a while...  ERROR:  Error installing rdiscount:          ERROR: Failed to build gem native extension.        C:/Ruby22/bin/ruby.exe -r ./siteconf20160313-1220-1i9eix7.rb extconf.rb  checking for random()... *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.  

Provided configuration options:

       --with-opt-dir          --without-opt-dir          --with-opt-include          --without-opt-include=${opt-dir}/include          --with-opt-lib          --without-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=C:/Ruby22/bin/$(RUBY_BASE_NAME)          --with-rdiscount-dir          --without-rdiscount-dir          --with-rdiscount-include          --without-rdiscount-include=${rdiscount-dir}/include          --with-rdiscount-lib          --without-rdiscount-lib=${rdiscount-dir}/lib  C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generat  e an executable file. (RuntimeError)  You have to install development tools first.          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:541:in `try_link0'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:556:in `try_link'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:735:in `try_func'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:1020:in `block in have_func'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:911:in `block in checking_for'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:351:in `block (2 levels) in postpo  ne'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:321:in `open'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:351:in `block in postpone'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:321:in `open'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:347:in `postpone'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:910:in `checking_for'          from C:/Ruby22/lib/ruby/2.2.0/mkmf.rb:1019:in `have_func'          from extconf.rb:5:in `<main>'    extconf failed, exit code 1    Gem files will remain installed in C:/Ruby22/lib/ruby/gems/2.2.0/gems/rdiscount-  2.1.8 for inspection.  Results logged to C:/Ruby22/lib/ruby/gems/2.2.0/extensions/x86-mingw32/2.2.0/rdi  scount-2.1.8/gem_make.out  

Can you please help me with the problem. I've been trying solve this problem for a month. Thank you.

Angular and Rails workflow

Posted: 13 Mar 2016 04:25 AM PDT

I'm working on a project where we decided to use Angular and Rails for front-end and back-end. I know Angular and the back-end guys know Rails, we don't want to mix this together. There are a lot of tutorials like this on how to set up this as a single page app, I don't want this.

  • Is it possible to create an API with rails that I can just call with Angular? If so, is there any tutorials on how to do this?
  • Wha'ts the benefits of creating a single page app and mixing Angular with Rails? From my front-end perspective this just seems confusing.

Showing whole page after ajax request in Ruby on Rails

Posted: 13 Mar 2016 01:55 AM PST

I'm creating one web application using RoR, but now I'm facing some issues like one I have used ajax now if request sent he return whole page, below my code

home_controller

def index   @post = Post.paginate(page: params[:recent], :per_page => 10).order('post_id DESC').joins("LEFT JOIN cities ON cities.city_name = city_name AND cities.city_id = post.city_id").where(["city_name LIKE ? ", "%#{params[:city_name]}%"])  end  

View

<form action="<% home_path %>" method="get">   <select name="city_name" class="form-control form-down" id="mySelect">    <option selected>Sort By</option>    <option value="Berlin">Berlin</option>    <option value="Tokyo">Tokyo</option>   </select>  </form>    <div id="mySelectedArea">    <% @post.each do |p| %>      <%= p.title %>      <%= p.location%>    <% end %>  </div>  

Ajax

<script type="text/javascript">   jQuery(function($) {     $("#mySelect").change(function() {      var city_name = $('select#mySelect :selected').val();      if(city_name == "") city_name="0";      $.ajax({       type: 'GET',       url: '<%= home_path %>',       data: 'city_name=' + city_name,       success: function(data) {          $("#mySelectedArea").html(data);         },       })       return false;     });   })   </script>  

Searchkick: Net::ReadTimeout when reindexing

Posted: 13 Mar 2016 12:40 AM PST

I recently upgraded my elasticsearch from 1.8 to 2.2 and problems have started since that time.

When I try to reindex products (40k), I get the Net::ReadTimeout error after 1000 products are reindex (the batch_size is set to 1000 by default).

I tried to set batch_size for searchkick to 1, 100, 200, and even then I get the Net::ReadTimeout error. When it was set to 1, it reindexed almost 20k products, if 100, only 100, if 200 only 200 products when it threw that error.

Do you know why this error occurs and how to avoid it? I have tried so many things (increase timeout from 1 to 10 minutes on the server, delete indexes, set the batch_size many times..) and nothing helped.

I have spent on this already few days and am totally stuck, will appreciate any ideas or help.

Thanks a lot for your time, Miroslav

Pass multiple select array of items from Angular 2 to Rails controller

Posted: 13 Mar 2016 12:29 AM PST

I have a Card which has many Hashtags.

Array of items from multiple select html tag is not accepted by Ruby on Rails controller.

Ruby on Rails Controller has the following:

def card_params    params.require(:card).permit(:name, hashtag_ids: [])  end  

In Angular 2:

// card-detail.component  export interface Card {   id: number;   title: string;   hashtag_ids: Array<any>;  }    export class CardDetailComponent implements OnInit, CanDeactivate {    public card: Card;    hashtag_ids: Array<any> = [];    form;      constructor(      fb: FormBuilder    ){      this.form = fb.group({        "title": ['', Validators.required],        "hashtags": ['', Validators.required]      })    }      save() {      this.card.hashtags.forEach(hashtag => {        this.hashtag_ids.push(hashtag.id);      });      this._service.update(this.card.id, this.card.title, this.datetime, this.hashtag_ids).subscribe(        err => {          return this._dialog.showError("Error. Please see log for details.");        },        () => {          this._dialog.showSuccess("Item updated successfuly.");        }      );    }    // card.service.component   update (id: number, name: string, expiration_date: string, hashtag_ids: any) : Observable<Card>  {        let body = JSON.stringify({ name, expiration_date, hashtag_ids });      let headers = new Headers({ 'Content-Type': 'application/json' });      let options = new RequestOptions({ headers: headers });        return this.http.patch(this._editCardUrl + id, body, options)                      .map(res => res.json());    }    // card-detail.html    <select ngControl="hashtags" [(ngModel)]="card.hashtag_ids" multiple>      <option *ngFor="#hashtag of card.hashtags" [value]="hashtag.id" selected>{{hashtag.name}}</option>    </select>    <div class="errorMessage" *ngIf="f.form.controls.hashtags.touched && !f.form.controls.hashtags.valid">Hashtag is required</div>  

Here is what is passed to controller:

Parameters: {"name"=>"Card 11", "hashtag_ids"=>[2, 1], "id"=>"1", "card"=>{"name"=>"Card 11"}}

As you see, hashtag_ids are not passed as part of Card object. Any ideas why and how to fix it?

thanks for help!

Draft.js / Rails Setup

Posted: 13 Mar 2016 12:26 AM PST

Is it possible to use DraftJs with a Rails framework ?

Currently using the following GEMs:

  1. gem 'js-routes'

  2. gem 'react-rails', '1.6.1'

  3. gem 'rails-assets-classnames'

On rails-assets, cannot find anything related to Draft.Js.

I would prefer not using npm (which seems to be required).

Associate a Readable User Dropdown in ActiveAdmin

Posted: 13 Mar 2016 12:25 AM PST

I guess not much help here. When you are trying to associate a user from a dropdown list, and imagine if you have 1000000 users, you would see the user instance. I need it to show the actual user's email address.

enter image description here

app/models/user.rb:

has_one :company  

app/models/company.rb:

belongs_to :user  

The link I was given has nothing to do with the dropdown's value.

Have I setup my rails association incorrectly? Funny thing was, using rails admin I had no issue in this department as I could associate a company when creating a user but not so with active admin.

All I want is when I select the User dropdown, as in picture, I'd see a list of user email addresses.

To use scope while looping in active_admin gem

Posted: 13 Mar 2016 12:29 AM PST

I was using active_admin gem, I want to use scope for keeping a status tab above table. In WelcomeCall I have made a column where status = "success" or nil. Now I have a made a scope in model with this status. This is that model:

class WelcomeCall < ActiveRecord::Base    attr_accessor :name, :area_independent, :categories     belongs_to :phone     scope :closed, -> {where('status=?',"success")}    scope :open, -> {where(:status => nil)}  end  

Now code for admin/welcome_call.rb

ActiveAdmin.register WelcomeCall do    permit_params :name, :area_independent    actions :index    filter :phone_id    filter :status       scope :closed    scope :open    collection_action :member_create, method: :post do    admin_welcome_call.member_create!    # redirect_to admin_welcome_call  end      index do    render 'index'  end  

Now inside this index.html.erb

<table>  <thead>  <tr>    <th>Number</th>    <th>Recording Url</th>    <th>Name</th>    <th>Categories</th>    <th>Areas</th>    <th>Status</th>    <th>Area_independant</th>    <th>Confirmation Box</th>  </tr>  </thead>    <tbody>    <% WelcomeCall.order("status").all.each_with_index do      |welcome_call,index| %>    <%= form_tag({:controller => "welcome_calls", :action =>           "member_create"}, {:method => "post", :remote => true, :id =>             "payment_order_paid_form_#{index}"}) do %>      <tr>      <% if welcome_call.status != "success" %>        <%= hidden_field_tag :welcome , welcome_call.id %>        <%= hidden_field_tag :index , index %>        <td><%= welcome_call.phone.phone rescue nil%></td>        <td><%= welcome_call.recording_url %></td>        <td><%= text_field_tag "name" %></td>        <td><%= select_tag "categories",       options_from_collection_for_select(Category.all, "id", "title"),       prompt: "Select something", multiple: true %><span></span></td>        <td><%= select_tag "areas",       options_from_collection_for_select(Area.all, "id", "area"), prompt:       "Select something", id: 'categories' %><span></span></td>        <td><b><%= welcome_call.status %></b></td>        <td><%= check_box_tag 'independent'%></td>        <td><%= submit_tag "Confirm", :class => "member-submit" %></td>      <% else %>        <td><%= welcome_call.phone.phone rescue nil%></td>        <td><%= welcome_call.recording_url %></td>        <td><%= text_field_tag "name" %></td>        <td><%= select_tag "categories",       options_from_collection_for_select(Category.all, "id", "title"),       prompt: "Select something", multiple: true %><span></span></td>        <td><%= select_tag "areas",       options_from_collection_for_select(Area.all, "id", "area"), prompt:       "Select something", id: 'categories' %><span></span></td>        <td><b><%= welcome_call.status %></b></td>        <td><%= check_box_tag 'independent'%></td>        <td><b> Already Submitted </b></td>      <% end %>    </tr>    <% end %>  <% end %>    </tbody>    </table>  

Problem: Here scope bar shows "open, closed" but it lists all the columns of WelcomeCall, but I want to list only those elements which are relevant to their scope bar.

undefined method `item_path' while working with ajax

Posted: 13 Mar 2016 06:15 AM PDT

Im trying to update my create item action to work with Ajax but Im getting an error of undefined methoditem_path` which i wasn't getting before when it was responding in regular html format. The item is created and saved but ajax doesn't seem to work properly though.

Here is my _from partial :

   <%= form_for [@user, item], remote: true do |f|%>        <div class="form-group">          <%= f.label :name, class: 'sr-only' %>          <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>        </div>        <%= f.submit "Submit Item", class: 'btn btn-primary pull-right' %>      <% end %>  

item#create:

  def create      @item = Item.new(item_params)      @item.user = current_user        if @item.save        flash[:notice] = 'Item saved successfully.'      else        flash[:alert] = 'Item not saved. Title is too short or missing. Please try again.'      end      respond_to do |format|        format.html        format.js      end    end  

create.js.erb:

$('.js-items').prepend("<%= escape_javascript(render(@item)) %>");     $('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: {user: @user , item: @item }) %>");  

User#show view

<div class='new_item'>  <%= render :partial => 'items/form', :locals =>{:item => Item.new , :user => @user} %>  </div>  <div class='js-items'>    <%= render @user.items %>  </div>  

routes:

user_items GET    /users/:user_id/items(.:format)          items#index                       POST   /users/:user_id/items(.:format)          items#create         new_user_item GET    /users/:user_id/items/new(.:format)      items#new        edit_user_item GET    /users/:user_id/items/:id/edit(.:format) items#edit             user_item GET    /users/:user_id/items/:id(.:format)      items#show                       PATCH  /users/:user_id/items/:id(.:format)      items#update                       PUT    /users/:user_id/items/:id(.:format)      items#update                       DELETE /users/:user_id/items/:id(.:format)      items#destroy  

The error im getting in rails s :

ActionView::Template::Error (undefined method `item_path' for #<#<Class:0x007fa4f0d30cd8>:0x007fa4f31b26b0>):      1: <%= form_for [@user, item], remote: true do |f|%>      2:   <div class="form-group">      3:     <%= f.label :name, class: 'sr-only' %>      4:     <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>    app/views/items/_form.html.erb:1:in `_app_views_items__form_html_erb__331698480542899910_70173200751480'    app/views/items/create.js.erb:2:in `_app_views_items_create_js_erb___3618987352886002527_70173200313760'    app/controllers/items_controller.rb:17:in `create'  

Time.now returns wrong result in test environment

Posted: 12 Mar 2016 11:09 PM PST

I'm running an RSpec test suite with capybara in my Rails app. When I put binding.pry inside of a test, and try Time.current, I get => Tue, 15 Dec 2015 00:06:30 UTC +00:00, which is three months ago. As far as my basic knowledge of geography goes, there isn't a time zone that has a 3 months difference with EST. So what am I missing here? :-)

Running same query in development environment (i.e. through rails console) returns correct result.

ruby socksify not working - Server doesn't reply (SOCKSError), although curl works

Posted: 12 Mar 2016 11:06 PM PST

I have a socks proxy verified by this command:

curl -x socks5://<socks_ip>:<socks_port> "http://canihazip.com/"  

When I try to attempt the same thing using ruby socksify gem as per the documentation:

require 'socksify/http'  proxy = '<socks_ip>'  port = '<socks_port>'  uri = URI.parse('http://canihazip.com/')  Net::HTTP.SOCKSProxy(proxy, port).start(uri.host, uri.port) do |http|    http.get(uri.path)  end  

gives error:

/home/resrev/.rvm/gems/ruby-2.2.2/gems/socksify-1.7.0/lib/socksify.rb:269:in `socks_receive_reply': Server doesn't reply (SOCKSError)      from /home/resrev/.rvm/gems/ruby-2.2.2/gems/socksify-1.7.0/lib/socksify.rb:259:in `socks_connect'      from /home/resrev/.rvm/gems/ruby-2.2.2/gems/socksify-1.7.0/lib/socksify.rb:174:in `initialize'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `open'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `block in connect'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/timeout.rb:74:in `timeout'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:878:in `connect'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:863:in `do_start'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:852:in `start'      from /home/resrev/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:583:in `start'      from /home/resrev/pubrevit/lib/tasks/test_rest_client_socks_proxy.rb:51:in `<main>'  

What am I missing?

$ ruby --version  ruby 2.2.2p95 (2015-04-13 revision 50295) [i686-linux]  $ rails --version  Rails 4.2.1  

rspec - command not found

Posted: 12 Mar 2016 11:12 PM PST

As part of assignment I am creating a basic website. When rails server is not running and I execute "rspec" for root directory, the rspec is executed. However tests fail. When I start rails server and execute rspec from another terminal window (after going to root directory), rspec doesnt work. I get the following message -

Tushars-MacBook-Pro:recipefinder tusharsaurabh$ rspec -bash: rspec: command not found

Please let me know, how to fix it.

spree cart is empty after page refresh

Posted: 12 Mar 2016 10:24 PM PST

I can add to cart once, but after I refresh the page, the cart is empty. I'm using Spree 2.4.

I check the value of @order in the orders controller#edit after I click 'add to cart':

[1] pry(#<Spree::OrdersController>)> @order  => #<Spree::Order id: 5, number: "R017142307", item_total: #<BigDecimal:89a8e10,'0.5E1',9(27)>, total: #<BigDecimal:89a8d20,'0.5E1',9(27)>, state: "cart", adjustment_total: #<BigDecimal:89a8bb8,'0.0',9(27)>, user_id: 1, completed_at: nil, bill_address_id: nil, ship_address_id: nil, payment_total: #<BigDecimal:89a8898,'0.0',9(27)>, shipping_method_id: nil, shipment_state: nil, payment_state: nil, email: "spree@example.com", special_instructions: nil, created_at: "2016-03-13 05:41:55", updated_at: "2016-03-13 06:18:01", currency: "USD", last_ip_address: "192.168.1.108", created_by_id: 1, shipment_total: #<BigDecimal:897bc80,'0.0',9(27)>, additional_tax_total: #<BigDecimal:897bb90,'0.0',9(27)>, promo_total: #<BigDecimal:897baa0,'0.0',9(27)>, channel: "spree", included_tax_total: #<BigDecimal:897b938,'0.0',9(27)>, item_count: 1, approver_id: nil, approved_at: nil, confirmation_delivered: false, considered_risky: false, guest_token: "kRau34G-dOY0Sh06Mk0_4g", canceled_at: nil, canceler_id: nil, store_id: 1, state_lock_version: 0>  

And line_items are there:

[3] pry(#<Spree::OrdersController>)> @order.line_items  => [#<Spree::LineItem id: 21, variant_id: 7, order_id: 5, quantity: 1, price: #<BigDecimal:88e8480,'0.5E1',9(27)>, created_at: "2016-03-13 06:18:01", updated_at: "2016-03-13 06:18:01", currency: "USD", cost_price: #<BigDecimal:88e78a0,'0.17E2',9(27)>, tax_category_id: 1, adjustment_total: #<BigDecimal:88e7738,'0.0',9(27)>, additional_tax_total: #<BigDecimal:88e7648,'0.0',9(27)>, promo_total: #<BigDecimal:88e7558,'0.0',9(27)>, included_tax_total: #<BigDecimal:88e7468,'0.0',9(27)>, pre_tax_amount: #<BigDecimal:88e7378,'0.0',9(27)>>]  

The views load and the shopping cart looks normal. However, after I refresh, it says the cart is empty..

@order is still the same, but the line_items have disappeared:

[1] pry(#<Spree::OrdersController>)> @order  => #<Spree::Order id: 5, number: "R017142307", item_total: #<BigDecimal:d3bfeb8,'0.5E1',9(27)>, total: #<BigDecimal:d3bfdc8,'0.5E1',9(27)>, state: "cart", adjustment_total: #<BigDecimal:d3bfc60,'0.0',9(27)>, user_id: 1, completed_at: nil, bill_address_id: nil, ship_address_id: nil, payment_total: #<BigDecimal:d3bf968,'0.0',9(27)>, shipping_method_id: nil, shipment_state: nil, payment_state: nil, email: "spree@example.com", special_instructions: nil, created_at: "2016-03-13 05:41:55", updated_at: "2016-03-13 06:18:01", currency: "USD", last_ip_address: "192.168.1.108", created_by_id: 1, shipment_total: #<BigDecimal:d3beb80,'0.0',9(27)>, additional_tax_total: #<BigDecimal:d3bea90,'0.0',9(27)>, promo_total: #<BigDecimal:d3be9a0,'0.0',9(27)>, channel: "spree", included_tax_total: #<BigDecimal:d3be838,'0.0',9(27)>, item_count: 1, approver_id: nil, approved_at: nil, confirmation_delivered: false, considered_risky: false, guest_token: "kRau34G-dOY0Sh06Mk0_4g", canceled_at: nil, canceler_id: nil, store_id: 1, state_lock_version: 0>    [2] pry(#<Spree::OrdersController>)> @order.line_items  => []  

I wasn't able to track down where the line_items are populated. Can someone help? Thanks.

Gem causes builds to fail. Point to local lib?

Posted: 12 Mar 2016 09:28 PM PST

I am using a gem which was recently updated. The last update is causing my builds to fail (uses uncompiled SCSS inside a .css file). I fixed the issue and created a pull request, but the author is not responding to the issue I opened and / or merging my PR.

Would it be a good idea to store the gem locally, push it to my production and staging and point to it the Gemfile until the issue gets fixed in the main repo?

Ruby - confirming data and sending to database

Posted: 12 Mar 2016 10:36 PM PST

This is not really a coding question, it is more about the approach. I am new to Ruby, but know several other languages. The idea is the following: I have a list of art classes, and the users can register to those classes (one-to-many) I created Users and ArtClasses models.

I also created Registrations model, which holds the cross-reference between the user and the class he subscribed to.

Basically, everything currently works already up to the last screen, where I have all the information about the class and the user - ID, email, and the rest.

My question is: What is the best approach to confirm the subscription and send the data to the database table (registrations model)? Should it be the form with non-editable fields and "Submit" button, or is there any more elegant solution? Again, this is about the approach. Thank you very much in advance!

Is it proper to have a static_pages controller?

Posted: 12 Mar 2016 08:48 PM PST

Is it proper to have a static_pages controller whose only purpose is to render static pages in large apps? Take the following scenario for instance:

You are developing a social network application and are devising the design of the application. You know you will need to be able to route some pages, like:

  • a landing page (for non-logged in users) at root route
  • a homepage/dashboard (for logged-in users) at root route

My question is: would you define a static_pages controller to handle the landing page and, later, when an authentication system is in place, check to see if [a user is] authenticated and replace templates? Or might you go without such a controller, opting to create a users_controller with a :before_action that checks for authentication, and redirects (on failure (read: unauthenticated users)) to the aforementioned landing page?

According to the Rails tutorial by Michael Hartl, the static_pages controller would be the way to go; however, my thinking is that that tutorial is geared at very new users of the framework and, perhaps, thus doesn't use the best of conventions in the name of simplicity.

What would be the preferred way, mainly in something of a large app (like Twitter, for example, or even StackOverflow), to handle such a situation?

Ruby Net::HTTP Start vs New

Posted: 12 Mar 2016 11:26 PM PST

Ruby Version: 1.9.3

http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net.html The documentation states that "If you wish to re-use a connection across multiple HTTP requests without automatically closing it you can use ::new instead of ::start"

http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-new This documentation states that "Creates a new Net::HTTP object without opening a TCP connection or HTTP session. "

Scenario:

My aim is use re-use HTTP and TCP connections as much as possible. If i am using Net::HTTP.start as my HTTP object, and if there is a significant delay between two successive calls ( > 2 minutes), the first call after the delay is failing with EOFError : end of file reached.

So, I am planning to swap Net::HTTP.start with Net::HTTP.new

Questions:

If i use new instead of start, will new re-use connections? or will it try to create a new HTTP and TCP connection everytime a HTTP call is made?

Will there be a performance impact because of this? What is the best way to handle in scenarios like these, where we want to make HTTP calls in a high volume traffic?

1 comment:

  1. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here
    Thank you. Your blog was very helpful and efficient For Me,Thanks for Sharing the information Regards..!!.. Ruby on Rails Online Training Bangalore

    ReplyDelete