Monday, August 15, 2016

How to use ActiveRecord aggregate functions with time zones? | Fixed issues

How to use ActiveRecord aggregate functions with time zones? | Fixed issues


How to use ActiveRecord aggregate functions with time zones?

Posted: 15 Aug 2016 08:31 AM PDT

This:

User.order(updated_at: :desc).first.created_at  

returns a value of type ActiveSupport::TimeWithZone. However, this:

User.maximum(:updated_at)  

returns a value of type Time.

What is the rational for this?

From the docs:

The value is returned with the same data type of the column, or nil if there's no row.

So what is the proper way of using ActiveRecord aggregate functions with the correct time zone - appending in_time_zone to all results?

User.maximum(:updated_at).in_time_zone  

Get absolute path of image saved by paperclip in Serializer of rails

Posted: 15 Aug 2016 08:25 AM PDT

I am saving images using Paperclip, while writing an API I need to get absolute path of image instead of relative path.

I have tried dozen of ways but they didn't worked, Actually URI.join or Request.host are not working in serializer.

How to get absolute path in serilaizer???

Render Highcharts inside Webix

Posted: 15 Aug 2016 08:06 AM PDT

I'm rendering Highcharts chart in the Rails app like this and it works fine:

  #container      #report-box        = render 'chart'  

However, I want to show this chart inside Webix scrollview. Now my code looks like this and is not working (no errors, only blank space where the chart should be):

#section3{:style => "display:none;"}    #container{:height => "800px", :width => "1100px"}      #report-box        = render 'chart'    webix.ui({view:"layout",      container:"scroll",      rows:[          {view: "scrollview", id: "sections", height: 600,           scroll: "y",           body:{              { id: "section_3", template: "html->section3", height: 300}           }      ]  });    function scroll(id){      $$("sections").showView("section_"+id);    };  

I would appreciate any ideas on how to make it work.

Get actual project in hook?

Posted: 15 Aug 2016 07:53 AM PDT

I'm trying to create my first Redmine plugin. Actually i'm trying to create a form in the issue sidebar (the view_layouts_base_sidebar hook) , and i can't find a way to get the current project

To get the current user, we can do this

User.current  

Now, i want to get the project of the current issue, do you know how to get it ? as Project.current doesn't exist

Thanks a lot

Javascript TypeError: variable is undefined

Posted: 15 Aug 2016 08:07 AM PDT

presently I am working on a Ruby on Rails app, and I am trying to get the below JS to work with the app. The first issue I came across was turbolinks 5.0 was preventing the page from loading the JS on initial load, and I would have to refresh the page in order to load the below JS. I did some googling, and came across this stackoverflow answer, but I can't seem to get the JS to run properly without throwing an error. Any and all help would be greatly appreciated.

orders.js

console.log('inside orders.js');    $(document).on('turbolinks:load', function() {  // Your JS here  var payment;    jQuery(function() {    Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));    return payment.setupForm();  });    payment = {    setupForm: function() {      return $('#new_order').submit(function() {        $('input[type=submit]').attr('disabled', true);        Stripe.card.createToken($('#new_order'), payment.handleStripeResponse);        return false;      });    },    handleStripeResponse: function(status, response) {      if (status === 200) {          // return alert(response.id);        $('#new_order').append($('<input type="hidden" name="stripeToken" />').val(response.id));        return $('#new_order')[0].submit();        } else {          // return alert(response.error.message);        return $('#stripe_error').text(response.error.message).show();        }    }  };  });  

Can't install because I don't have high enough Ruby version, but I do

Posted: 15 Aug 2016 08:10 AM PDT

I'm trying to add a widget to a dashboard. I've cloned the widget to the correct directory and copied files over to the relevant locations. The final thing to do is run this line:

bundle install   

Everything goes well until I get line :

Gem::InstallError: activesupport requires Ruby version >= 2.2.2.    Make sure that `gem install activesupport -v '5.0.0.1'` succeeds before  bundling.  

So I've installed that separately:

sudo gem install activesupport -v 5.0.0.1  Successfully installed activesupport-5.0.0.1  

But when I try to run "bundle install" I get the same error.

I even checked by ruby version, and its high enough:

ruby -v  ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]  

What am I doing wrong? Is it choosing to use a lower version of ruby?

How to write validation for enum in rails

Posted: 15 Aug 2016 08:38 AM PDT

I have an enum in one of my model in my api

enum pay_method: {    cash: 0,    card: 1  }  

I want to have validation for this enum but i can not do that . I wrote a validation in my model for that but it did not take any effect

How do you merge two jquery posts into one in coffeescript?

Posted: 15 Aug 2016 07:53 AM PDT

I need to merge these two objects:

{ swim_lane_id: $(this).closest('ul').data('lane-id') }  

+

$(this).sortable('serialize')  

into one object that can be sent as the [DATA] in a $.post:

$.post($(this).data('update-url'), [DATA] );  

$.merge only gives swim_lane_id and an id that is part of the update-url data tag but doesn't give the serialized data from the sortable list.

I basically need to be able to pass these through in one post because the update-url data tag routes to a controller action in my Rails application and I need to know which list is being updated for every update action sent to it.

Gem load error when trying to use RinRuby

Posted: 15 Aug 2016 08:02 AM PDT

I am trying to use the RinRuby gem, but when trying to fire up my rails server I get the following error:

 in require': There was an error while trying to load the gem 'rinruby'.     (Bundler::GemRequireError)  Gem Load Error is: No such file or directory - R  Backtrace for gem load error is:  /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/gems/rinruby-2.0.3/lib/rinruby.rb:164:in `popen'  /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/gems/rinruby-2.0.3/lib/rinruby.rb:164:in `initialize'  /Users/reinierverbeek/.rvm/gems/ruby-2.3.0/gems/rinruby-2.0.3/lib/rinruby.rb:789:in `new'  

I have R installed and my .bash-profile file looks like this:

PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"  export PATH    [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*  export R_HOME="/Library/Frameworks/R.framework/Resources"  source ~/.profile  

I added this bash file, because I also noticed that I am not able to execute R scripts from the CLI using Rscript, but I have to include the whole path

"/Library/Frameworks/R.framework/Resources/Rscript"  

I also tried to edit my path with the following:

PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}:/Library/Frameworks/R.framework/Resources/Rscript"  

but this didn't help

devise bug! devise_for :installs bug

Posted: 15 Aug 2016 07:27 AM PDT

cannot run the command linedevise_for :installs bug! keep getting this:

/Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/nokogiri-1.6.8/lib/nokogiri/nokogiri.bundle: [BUG] Segmentation fault at 0x00000000000418 ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin14.0]

-- Crash Report log information -------------------------------------------- See Crash Report log file under the one of following: * ~/Library/Logs/CrashReporter * /Library/Logs/CrashReporter * ~/Library/Logs/DiagnosticReports * /Library/Logs/DiagnosticReports for more details.

-- Control frame information ----------------------------------------------- c:0046 p:-17556424632272 s:0145 e:000144 TOP [FINISH] c:0045 p:---- s:0143 e:000142 CFUNC :require c:0044 p:0020 s:0139 e:000138 BLOCK /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/nokogiri-1.6.8/lib/nokogiri.rb:32 c:0043 p:0149 s:0136 e:000135 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/nokogiri-1.6.8/lib/nokogiri.rb:28 [FINISH] c:0042 p:---- s:0134 e:000133 CFUNC :require c:0041 p:0060 s:0130 e:000129 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/loofah-2.0.3/lib/loofah.rb:3 [FINISH] c:0040 p:---- s:0128 e:000127 CFUNC :require c:0039 p:0015 s:0124 e:000123 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/rails-html-sanitizer-1.0.3/lib/rails-html-sanitizer.rb:2 [FINISH] c:0038 p:---- s:0122 e:000121 CFUNC :require c:0037 p:0023 s:0118 e:000117 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/sanitize_helper.rb:3 [FINISH] c:0036 p:0025 s:0116 e:000114 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/text_helper.rb:32 c:0035 p:0011 s:0113 e:000112 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/text_helper.rb:29 c:0034 p:0011 s:0111 e:000110 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/text_helper.rb:6 c:0033 p:0025 s:0109 e:000108 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/text_helper.rb:4 [FINISH] c:0032 p:0038 s:0107 e:000105 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/form_tag_helper.rb:18 c:0031 p:0011 s:0104 e:000103 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/form_tag_helper.rb:14 c:0030 p:0011 s:0102 e:000101 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/form_tag_helper.rb:8 c:0029 p:0041 s:0100 e:000099 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/form_tag_helper.rb:6 [FINISH] c:0028 p:---- s:0098 e:000097 CFUNC :require c:0027 p:0031 s:0094 e:000093 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers/form_helper.rb:4 [FINISH] c:0026 p:0391 s:0092 e:000090 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers.rb:50 c:0025 p:0011 s:0089 e:000088 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers.rb:4 c:0024 p:0017 s:0087 e:000086 TOP /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/actionview-4.2.6/lib/action_view/helpers.rb:3 [FINISH] c:0023 p:0012 s:0085 e:000083 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/sprockets-rails-3.1.1/lib/sprockets/rails/context.rb:7 c:0022 p:0011 s:0082 e:000081 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/sprockets-rails-3.1.1/lib/sprockets/rails/context.rb:6 c:0021 p:0011 s:0080 e:000079 CLASS /Users/lironbarkalifa/Desktop/recipe_box/vendor/bundle/gems/sprockets-rails-3.1.1/lib/sprockets/rails/context.rb:5

Any ideas what to do?

In Rails, how to call an AJAX function and then refresh page when its complete?

Posted: 15 Aug 2016 07:37 AM PDT

I have a form where I if a user changes the value in one of the drop-down-lists then it needs to change some controls on the form. The way it's currently set up...

  1. On drop-down-list change, executes an AJAX call to save the form with new value
  2. Before the "update" method executes on my object I mark deleted fields that do not pertain to the new value that was changed
  3. In the success function of the AJAX call it executes a location.reload()

The current problem is that the reload occurs sometimes before the auto-save method has completed. How can I only reload the page until after the auto-save has fully completed? I don't want to set async: false in the $.ajax because it freezes the entire page before my message to the user is shown telling them to please wait. Please let me know if I've forgotten any code to include below thanks!

reports.coffee

  autoSavePost = (reload) ->    console.log('autosave executed');    $.ajax      type: 'PUT'      url: '/reports/autosave'      data: $('#report-form').serialize()      dataType: 'script'      success: (data) ->        if reload          setTimeout(location.reload(), 5000);        return true      error: (xhr, ajaxOptions, thrownError) ->        console.log xhr.responseText.substr(0,1500)        return false    # schedule the next autosave    if $('#auto-save').length      setTimeout autoSavePost, 60000    else      return false      return    $ ->        $(document).on 'change', '#report_position_id', (evt) ->          $.blockUI({ message: '<h5>Please wait, "Position Graded" is being changed...</h5>' });          # grey out screen with message until page reloads.          autoSavePost(true)          return  

How to test that JSON-only controller returns 406

Posted: 15 Aug 2016 07:57 AM PDT

I have a controller that should only accept application/json or /. I check this in the controller class:

...  include ActionController::MimeResponds    before_action :require_json    def require_json    respond_to :json  end  ....  

That works pretty well, although there is an UnknownFormat error in the log every time a client uses an invalid accept header. The controller correctly returns HTTP 406 Not acceptable.

In the test I write:

...  test 'do not accept plain text' do    assert_raises ActionController::UnknownFormat do      get '/api/v1/ping', headers: {'Accept' => 'text/plain'}    end    assert_response :not_acceptable  ...  

Then Rake aborts with undefined method error at accept_response since the response is nil. I assume it is not set the normal execution flow aborts at the unknown format exception. But if I do not assert the exception the test will just abort with it.

Is it a good idea to throw an exception at every 406? How can I test that I get a 406 returned?

How to rewrite this ActiveRecord qurey to MySQL?

Posted: 15 Aug 2016 07:19 AM PDT

I have this query from Rails code:

cars = Car.where('cars.status = 0 AND cars.new = 0')  cars.each do |car|    SharedCar.create(car_id: car.id, owner_id:  OWNER_ID)  end    

and I would need to run this query directly to MySQL console. How to create a MySQL that would does the same as the ActiveRecord above?

EDIT: Focus is obviously on how to combine the first and second query, not on how to load the fist query in MySQL.

Thank you.

How to negate a scope? [duplicate]

Posted: 15 Aug 2016 06:51 AM PDT

This question already has an answer here:

Below is a scope that I'm using:

scope :applying, -> { where(admin_confirmed_at: nil) }  

Now, I would like to use another scope named confirmed that is exactly opposite to applying: it searches for the records where admin_confirmed_at is not nil. How can I write it using the predefined scope applying?

I have tried following:

scope :confirmed, -> { !applying }  scope :confirmed, -> { not.applying }  

Eventually, I had to write following:

scope :confirmed, -> { where.not(admin_confirmed_at: nil)  }  

C Stack usage error while using RSRuby with rails

Posted: 15 Aug 2016 05:55 AM PDT

I try to use RSRuby to execute some R script within my rails project. I created a method inside a module, I call this module from a model and want to store the return value.

When I execute this method (from the model > module) using the rails console everything works fine. But when I try to execute this same method within my rails application I get the following error:

Error: C stack usage  17589268476924 is too close to the limit  Error: C stack usage  17589268476972 is too close to the limit  Error: C stack usage  17589268476876 is too close to the limit  Fatal error: unable to initialize the JIT  

This error is not related to the R Script (I tried several very simple scripts, but get the same error regardless of the R code I execute). Does anybody have an idea how I could fix this problem?

Apart from this error I found RSRuby the most suitable way to integrate R within Ruby, I had other problems when trying to use RinRuby (a gem load error when starting the rails server, because R could not be found). Executing code from the CLI seems inefficient and returns the output as a string, which is in this case also not feasible.

error while rails s, and i have nodejs

Posted: 15 Aug 2016 05:19 AM PDT

C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2/lib/bundler/ runtime.rb:80:in rescue in block (2 levels) in require': There was an error whi le trying to load the gem 'uglifier'. (Bundler::GemRequireError) from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2 /lib/bundler/runtime.rb:76:inblock (2 levels) in require' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2 /lib/bundler/runtime.rb:72:in each' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2 /lib/bundler/runtime.rb:72:inblock in require' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2 /lib/bundler/runtime.rb:61:in each' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2 /lib/bundler/runtime.rb:61:inrequire' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/bundler-1.11.2 /lib/bundler.rb:99:in require' from C:/Sites/MyRubyBlog/config/application.rb:7:in' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.5 .1/lib/rails/commands/commands_tasks.rb:78:in require' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.5 .1/lib/rails/commands/commands_tasks.rb:78:inblock in server' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.5 .1/lib/rails/commands/commands_tasks.rb:75:in tap' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.5 .1/lib/rails/commands/commands_tasks.rb:75:inserver' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.5 .1/lib/rails/commands/commands_tasks.rb:39:in run_command!' from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.5 .1/lib/rails/commands.rb:17:in' from bin/rails:4:in require' from bin/rails:4:in'

Display Errors For Nested Form

Posted: 15 Aug 2016 04:55 AM PDT

I have a nested form in my view;

<%= simple_form_for @form, url: url do |f| %>      <%= f.input :name %>      <%= f.input :description, as: :text %>      <%= f.fields_for :account, { :class => 'field' } do |ff| %>      <%= ff.collection_radio_buttons(:account_type_id, AccountType.all, :id, :name, selected: ff.object.account_type_id) { |b| radio_button_builder(b) } %>    <% end %>  

Here is my Form object (extending Reform);

class ProgrammeForm < ApplicationForm    properties :name, :description, validates: {presence: true}      property :account do      property :account_type_id      validates :account_type_id, presence: true    end  end  

If I submit the form without filling in any fields, then my <% if @form.errors.any? %> partial will print out three errors;

3 Errors prohibited this from being saved:  Name can't be blank  Description can't be blank  Account account type can't be blank  

But there is no "error-looking" HTML on my nested form (the account_type stuff). Name and description are fine (as those are fairly straight forward). But;

  1. fields_for doesn't put a div wrapper around the radio buttons collection to begin with.
  2. There is no other indication that there was an error on this field (like with name and description).

How can I address these two points?

Unable to deploy Rails App to DigitalOcean because of unsupported key type

Posted: 15 Aug 2016 05:20 AM PDT

I have configured the droplet in DO and nginx is up and running successfully. I followed the guide on DO on deploying to server via Capistrano. I can ssh into the server without entering my password. But on running bundle exec cap production deploy:initial I'm getting a very weird error:

cap aborted! NotImplementedError: unsupported key type�pl+�lI���D�����U����X��K\�L�[�\� �M�\� �M�A?d��h"sU�Ǐ�2�?h��a 5G͕�E���%!Cg��j�|��tu�yL*�'/9�s۷'

I'm using rsa SSH key and this has been working with many (>10) servers seamlessly. I tried to remove the ssh_options param from my deploy/production.rb file. This should ask for the server password before (I guess?). But I get the same error, leading me to suspect that something else is tripping me up.

Gem Versions:

net-ssh (3.2.0) capistrano (3.6.0) sshkit (1.11.2)

How to use subdomain with ActiveAdmin on rails

Posted: 15 Aug 2016 04:50 AM PDT

I'm trying to access the ActiveAdmin with subdomain "admin.localhost.local:3030" instead of namespace "localhost:3030/admin". I looked it up and I found that I should change the default namespace in "config/initializers/active_admin.rb" to false

config.default_namespace = false  

and I surrounded the routes in "routes.rb" with subdomain constraints

constraints :subdomain => "admin" do      ActiveAdmin.routes(self)  end  

also, I changed "/etc/hosts" localhost line to be able to test on my machine

127.0.0.1    admin.localhost.local  

but for some reason, it still doesn't work. I'm trying to access the subdomain by writing admin.localhost.local:3030 and this is what I get from the browser: "The admin.localhost.local page isn't working. admin.localhost.local redirected you too many times."

Rails, align dynamic elements using bootstrap

Posted: 15 Aug 2016 05:58 AM PDT

I'm trying to make my products display view and align them using bootstrap, like in my model. The problem is that, because elements are create dynamically, I can' t do a big bootstap div for all my elements, in order to set an offset, and if I just set my elem size, they are no aligned at all : I displayed them with black background to see better how each div is positioned.

  <% @products.each do |product| %>      <div class="entry col-xs-4 col-xs-offset-0 col-lg-4 col-lg-offset-0">        <div class="product_img img-responsive">          <%= image_tag(product.image_url)%>        </div>      <div class="product_description">        <h3><%= product.title %></h3>          <%= sanitize(product.description)%>        <div class="price_line">          <span class="price"><%=number_to_currency(product.price)%></span>      </div>    </div>  </div>

my model is : enter image description here

How can I do please?

factory_girl, transient attribute creates two records

Posted: 15 Aug 2016 04:38 AM PDT

I have the following factories set up

factories/request.rb

FactoryGirl.define do

factory :request do      serves 1      instructions "I want cheap food."      allergens "Nothing special"      active true        transient do          requested_by nil          suburb nil      end        after(:create) do |request, factory|          if factory.requested_by              FactoryGirl.create(:request, customer: factory.requested_by)          end          if factory.suburb                FactoryGirl.create(:request, suburb: factory.suburb)          end      end  end    trait :with_customer do      customer  end  

end

factories/customer.rb

FactoryGirl.define do      factory :customer do      address "321 Sample Street"      allergies "Nuts"      dietary_info "Nothing"      account  end    trait :with_request do      transient do          request_count 5      end        after(:create) do |request, evaluator|          create_list(request, evaluator.request_count, customer: customer)      end  end    trait :with_diet do      diet_info factory: :diet_info  end    trait :with_suburb do      suburb    end  end  

And I am trying to test that a customer's request is returned with the following Rspec example:

it "returns active request assuming there is one" do          cus = create(:customer)          expect(cus.requests.first).to be_nil            re = create(:request, requested_by: cus)          expect(cus.requests.first).not_to be_nil          # this fails. expected 1, got 2          expect(cus.requests.first.id).to eq 1              expect(re.id).to eq (1)              expect(cus.has_active_request?).to be true          # this fails as well          expect(cus.active_request).to eq(re)  end  

Output

expected: #<Request id: 1, customer_id: nil, suburb_id: nil, serves: 1, instructions: "I want cheap food.", all...othing special", active: true, created_at: "2016-08-15 11:33:05", updated_at: "2016-08-15 11:33:05">   got: #<Request id: 2, customer_id: 1, suburb_id: nil, serves: 1, instructions: "I want cheap food.", aller...othing special", active: true, created_at: "2016-08-15 11:33:05", updated_at: "2016-08-15 11:33:05">     (compared using ==)  

The last expectation fails as well. It seems like two Request objects are created and cus and re refer to different ones, which I don't understand how I managed to create that relationship. This makes testing impossisble because i don't have a reference to the actual request stored in cus.active_request (the model method I am trying to test).

Missing PaperClip Image

Posted: 15 Aug 2016 04:21 AM PDT

Controller File class HandymenController < ApplicationController before_action :find_handyman, only: [:show, :edit, :update, :destroy]

def index      if params[:profession].blank?          @handymen = Handyman.all.order("created_at DESC")      else          @profession_id = Profession.find_by(name: params[:profession]).id          @handymen = Handyman.where(:profession_id => @profession_id).order("created_at DESC")      end   end    def show  end     def new      @handyman = current_user.handymen.build      @professions = Profession.all.map{ |p| [p.name, p.id] }  end    def create      @handyman = current_user.handymen.build(handyman_params)      @handyman.profession_id = params[:profession_id]        if @handyman.save          redirect_to root_path      else          render 'new'      end  end     def edit      @professions = Profession.all.map{ |p| [p.name, p.id] }  end    def update      @handyman.profession_id = params[:profession_id]      if @handyman.update(handyman_params)          redirect_to handyman_path(@handyman)      else          render 'edit'      end  end    def destroy      @handyman.destroy      redirect_to root_path  end    private    def handyman_params      params.require(:handyman).permit(:name, :location, :phone_number, :profession_id, :handyman_img)  end     def find_handyman      @handyman = Handyman.find(params[:id])  end  

end

Model File class Handyman < ActiveRecord::Base belongs_to :user belongs_to :profession

has_attached_file :handyman_img, styles: { handyman_index: "250x350>", handyman_show: "325x475>" } validates_attachment_content_type :handyman_img, content_type: /\Aimage/.*\Z/ end

ErrorLog Started GET "/handyman_imgs/handyman_index/missing.png" for ::1 at 2016-08-15 10:29:24 +0000

ActionController::RoutingError (No route matches [GET] "/handyman_imgs/handyman_index/missing.png"): actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:21:in call' web-console (2.3.0) lib/web_console/middleware.rb:28:inblock in call' web-console (2.3.0) lib/web_console/middleware.rb:18:in catch' web-console (2.3.0) lib/web_console/middleware.rb:18:incall' actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in call' railties (4.2.6) lib/rails/rack/logger.rb:38:incall_app' railties (4.2.6) lib/rails/rack/logger.rb:20:in block in call' activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:inblock in tagged' activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in tagged' activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:intagged' railties (4.2.6) lib/rails/rack/logger.rb:20:in call' actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:incall' rack (1.6.4) lib/rack/methodoverride.rb:22:in call' rack (1.6.4) lib/rack/runtime.rb:18:incall' activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in call' rack (1.6.4) lib/rack/lock.rb:17:incall' actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in call' rack (1.6.4) lib/rack/sendfile.rb:113:incall' railties (4.2.6) lib/rails/engine.rb:518:in call' railties (4.2.6) lib/rails/application.rb:165:incall' rack (1.6.4) lib/rack/lock.rb:17:in call' rack (1.6.4) lib/rack/content_length.rb:15:incall' rack (1.6.4) lib/rack/handler/webrick.rb:88:in service' C:/Ruby21-x64/lib/ruby/2.1.0/webrick/httpserver.rb:138:inservice' C:/Ruby21-x64/lib/ruby/2.1.0/webrick/httpserver.rb:94:in run' C:/Ruby21-x64/lib/ruby/2.1.0/webrick/server.rb:295:inblock in start_thread'

Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/routes/_route.html.erb (4.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/routes/_table.html.erb (106.1ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout (332.3ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (1.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (1.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (1.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (216.2ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.0ms) Rendered C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (335.3ms)

Rails: Refile gem (attachment_image_tag prints wrong URL)

Posted: 15 Aug 2016 05:48 AM PDT

I'm using refile gem for file uploading and I'm uploading files directly to my amazon s3 public bucket. The files are being uploaded just fine to following URL:

https://s3.amazonaws.com/{bucket-name}/store/6309035935359dca1ef549170e7facac9ab3553ad53946cea0bcb8335475

I'm using amazon cloudfront to serve these assets from s3, so the cloudfront url, for the asset given above, is something like this:

https://{distribution-name}.cloudfront.net/store/6309035935359dca1ef549170e7facac9ab3553ad53946cea0bcb8335475

The both urls when accessed directly through browser works fine. To display this asset in my app view file I'm using refile gem following helper function:

attachment_image_tag(@post, :profile_img, :fill, 350, 350)

Now the issue is, this helper method prints a URL something like this:

https://{distribution-name}.cloudfront.net/attachments/5845d0a97dc77a57b5b05742a1eb26d629d7cdaa/store/fill/350/350/6309035935359dca1ef549170e7facac9ab3553ad53946cea0bcb8335475/file

As this URL is different from above cloudfront URL, it is not displaying the image. How do I force attachment_image_tag function to print the correct cloudfront URL?

Why am I getting singleton cant be dumped err?

Posted: 15 Aug 2016 04:09 AM PDT

When I try to add a variable value into session, I am getting singleton cant be dumped err.

Here is the value in the varibale

[      [0] {                                          :id => "574ecb43a7a5bb44c000443b",                                         :_id => "574ecb43a7a5bb44c000443b",                                      :active => true,                                :capabilities => {              :network_connections => [                  [0] {                      :type => "ethernet-wan",                      :name => "wan"                  },                  [1] {                      :type => "ethernet-lan",                      :name => "lan"                  },                  [2] {                      :type => "wifi",                      :name => "wlan"                  },                  [3] {                      :type => "cellular",                      :name => "wwan"                  }              ]          },                               :commander_ids => [],                                  :created_at => "2016-05-11T15:46:12+00:00",                                  :deleted_at => nil,                         :firmware_upgradable => true,                                :ingestor_ids => [],                  :last_known_translator_port => nil,                            :long_description => "this is a liong desc",                                :manufacturer => "test_sushant",                                       :model => "sushant_test",                                        :name => "zxc",          :parent_gateway_data_source_type_id => nil,                                    :rule_ids => [],                                    :software => "qwe",                                  :translator => "edge",                                        :type => "asd",                                  :updated_at => "2016-05-11T15:46:12+00:00",                                     :user_id => "572adee5a7a5bb320b000852"      },  

The variable is an array of objects. I do not know why this is causing an err.

How to print JSON object in browser console, using ruby controller?

Posted: 15 Aug 2016 05:29 AM PDT

I want to print a JSON object in the browser's console, I searched a lot but I din't find any appropriate result.

Here is my ruby controller:

class ScheduleTime < ApplicationController    available_schedule = ScheduleTimeSlot.where(:doctor_id => params[:dr_id],:date=>params[:for_date].to_date,:status=>"vacant",:archive=>false).reorder(:start_time)    render :json =>{:available_schedules=>available_schedules}    //here I need a syntax that print the available_schedule on browser console (if possible) or ruby console, so I can debug it properly.    end  

Thanks In Advance

Sphinx (ThinkingSphinx) with no down time?

Posted: 15 Aug 2016 04:06 AM PDT

I am currently using Sphinx with ThinkingSphinx gem for Rails.

I am using delta indices with scheduled indexing via cron. The problem is, for each deploy, I restart the searchd process (configure before starting again) based off the docs.

I deploy around 5 times a day and it's not acceptable for me that search goes down every time I do. Is there really a need to restart sphinx every time? Surely, there is a way to achieve no downtime?

Rails5 migration: can't quote Array

Posted: 15 Aug 2016 04:54 AM PDT

I try to migrate my app from Rails 4 to Rails 5 Here is my migration:

class AddRevealedIdsToUser < ActiveRecord::Migration[5.0]    def change      add_column :users, :revealed_ids, :text, default: []    end  end  

And model:

serialize :revealed_ids  

It worked perfectly in Rails 4, now I have an error:

== 20160416214334 AddRevealedIdsToUser: migrating =============================  -- add_column(:users, :revealed_ids, :text, {:default=>[]})  rails aborted!  StandardError: An error has occurred, this and all later migrations canceled:    can't quote Array  /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/abstract/quoting.rb:177:in `_quote'  /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/postgresql/quoting.rb:96:in `_quote'  

how to solve?

after_update callback calls on page refresh

Posted: 15 Aug 2016 04:13 AM PDT

my after update callback calls when i refresh the page and I dont want it to do that. Once i refresh the Room show page the room.availability automatically changes to false.

class BookRoom < ApplicationRecord  has_many :rooms, :through => :room_customers  after_update :add_dynamic_change    def add_dynamic_change  room = Room.find self.room  room.availability = false  room.save!  end    

but anytime I refresh the Room's show page, the callback is called even without updating the BookRoom record?

Controller

    class BookRoomsController < ApplicationController        before_action :set_book_room, only: [:show, :edit, :update]          def index           @search = BookRoom.ransack(params[:q])           @book_rooms = @search.result(distinct: true).desc_order        end             def show        end             def create           @customer = Customer.find(params[:customer_id])           @customer_room = @customer.book_rooms.create(book_rooms_params)          flash[:notice] = "Customer has been added to room"          redirect_to customer_path(@customer)        end           def destroy           @customer = Customer.find(params[:customer_id])           @customer_room = @customer.book_rooms.find(params[:id])          @customer_room.destroy          flash[:notice] = "Customer room has been deleted"          redirect_to customer_path(@customer)        end           def edit         end            def update           @book_room.update(book_rooms_params)          redirect_to @book_room          flash[:notice] = "Customer has checked out"        end             private           def set_book_room          @book_room = BookRoom.find(params[:id])        end             def book_rooms_params           params.require(:book_room).permit(:room, :first_name, :last_name, :phone_number, :checked_out)        end         end  

rooms controller

class RoomsController < ApplicationController        before_action :set_room, only: [:show, :edit, :update, :destroy]          # GET /rooms        # GET /rooms.json        def index          @rooms = Room.all        end          # GET /rooms/1        # GET /rooms/1.json        def show          @book_rooms = BookRoom.where room_number: @room.room_number          @room.book_rooms << @book_rooms          @lodged = @room.book_rooms.group(:first_name)        end          # GET /rooms/new        def new          @room = Room.new        end          # GET /rooms/1/edit        def edit        end          # POST /rooms        # POST /rooms.json        def create          @room = Room.new(room_params)            respond_to do |format|            if @room.save              format.html { redirect_to @room, notice: 'Room was successfully created.' }              format.json { render :show, status: :created, location: @room }            else              format.html { render :new }              format.json { render json: @room.errors, status: :unprocessable_entity }            end          end        end          # PATCH/PUT /rooms/1        # PATCH/PUT /rooms/1.json        def update          respond_to do |format|            if @room.update(room_params)              format.html { redirect_to @room, notice: 'Room was successfully updated.' }              format.json { render :show, status: :ok, location: @room }            else              format.html { render :edit }              format.json { render json: @room.errors, status: :unprocessable_entity }            end          end        end          # DELETE /rooms/1        # DELETE /rooms/1.json        def destroy          @room.destroy          respond_to do |format|            format.html { redirect_to rooms_url, notice: 'Room was successfully destroyed.' }            format.json { head :no_content }          end        end          private          # Use callbacks to share common setup or constraints between actions.          def set_room            @room = Room.find(params[:id])          end            # Never trust parameters from the scary internet, only allow the white list through.          def room_params            params.require(:room).permit(:room_number, :availability, :neatness, :room_category_id)          end      end  

Cannot display image inside email in rails

Posted: 15 Aug 2016 05:37 AM PDT

I am trying to display my logo inside an email in my rails app. My image is located in assets/images and in the public folder. However my image seem to be never found by the app. How can I include my image in the email ? Here's my layout mailer.html.erb where the image is included inside image_tag

<html>    <body>    <div style= "text-align: center;">      <%= image_tag "quickbed_logo.png", style: "width: 200px;"%>    </div>      <%= yield %>    </body>  </html>  

Remove white space from params

Posted: 15 Aug 2016 04:08 AM PDT

I have a piece of code which collects params from a form and reads them into invite as I can see. The problem is one of these parameters is an email which I want to ensure has no trailing whitespace. How could I apply strip to invite and all of the params fed into it?

def invite_partner    return unless invite = params[:partner]    return flash.now[:error] = 'Please select a role' unless role = Role.where(klass: invite[:klass], name: 'Admin').first    return flash.now[:alert] = 'Email address already in use' if User.where(email: invite[:email]).first      raise 'bugger' unless current_user.is_a?(User)      partner_invite = PartnerInviteMailer.invite(current_user.operator, invite[:email], invite[:klass], Portal.portal_for_hostname(host_from_request))    partner_invite.deliver      flash.now[:success] = "#{invite[:klass]} invited, email sent to #{invite[:email]}"  end  

No comments:

Post a Comment