Tuesday, October 4, 2016

How to stub RSpec update action? | Fixed issues

How to stub RSpec update action? | Fixed issues


How to stub RSpec update action?

Posted: 04 Oct 2016 07:45 AM PDT

New to RSpec and having trouble stubbing out an update method (needs to be stubbed) and am running into this error. I have tried a bunch of different ways and can't seem to solve it. I tried to include only the necessary code.

/spec/controllers/admin/business_controller_spec.rb:

require 'spec_helper'    RSpec.describe Admin::BusinessesController, type: :controller do    render_views      before(:all) do      @business = build_stubbed(:business)    end      describe '#update' do      before(:each) do        allow(Business).to receive(:find).and_return(@business)        @new_name = Faker::Company.name        @params = { id: @business.id, business: { name: @new_name } }      end        it 'updates business name' do        expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: @business.confirm_flag, phone_primary: @business.phone_primary).and_return(true)        xhr :patch, :update, id: @business.id, business: { name: @new_name }        expect(@business.name).to eq(@new_name)      end    end  end  

/app/controllers/admin/businesses_controller.rb

class Admin::BusinessesController < Admin::BaseAdminController      def update      @business.update_attributes(business_params)    end      def business_params      params.require(:business).permit(:name, :active_flag).merge(confirm_flag: true, phone_primary: '')    end    end  

When I run this test I get this error:

Failures:      1) Admin::PartnersController#update updates partner name   Failure/Error: @partner.update_attributes(partner_params)       #<Partner:0x007fc43c4f5738> received :update_attributes with unexpected arguments       expected: ({:name=>"Fadel, Larson and Hettinger", :confirm_flag=>true, :phone_primary=>"7832900175"})            got: ({"name"=>"Fadel, Larson and Hettinger", "confirm_flag"=>true, "phone_primary"=>""})     Diff:     @@ -1,4 +1,4 @@     -[{:name=>"Fadel, Larson and Hettinger",     -  :confirm_flag=>true,     -  :phone_primary=>"7832900175"}]     +[{"name"=>"Fadel, Larson and Hettinger",     +  "confirm_flag"=>true,     +  "phone_primary"=>""}]  

So it looks like the phone_primary is causing the problem and I change my test expectation line to be:

  describe '#update' do      before(:each) do        allow(Business).to receive(:find).and_return(@business)        @new_name = Faker::Company.name        @params = { id: @business.id, business: { name: @new_name } }      end        it 'updates business name' do        expect(@business).to receive(:update_attributes).with(name: @new_name, confirm_flag: @business.confirm_flag, **phone_primary: ''**).and_return(true)        xhr :patch, :update, id: @business.id, business: { name: @new_name }        expect(@business.name).to eq(@new_name)      end    end  

and i get the failure:

Failures:      1) Admin::PartnersController#update updates partner name   Failure/Error: expect(@partner4.name).to eq(@new_name)       expected: "Flatley Inc"          got: "Samara Kuhic"  

And now the names aren't matching

binding_of_caller -- Gem::Ext::BuildError: ERROR: Failed to build gem native extension

Posted: 04 Oct 2016 07:43 AM PDT

I encounter this issue with ruby version ruby 1.9.3p551, OSX EI Capitan, when i am trying to run below command

gem install binding_of_caller -v '0.7.1'  

and the description of error as bellow:

Building native extensions. This could take a while... ERROR: Error installing binding_of_caller: ERROR: Failed to build gem native extension.

    current directory: /usr/local/lib/ruby/gems/1.9.1/gems/binding_of_caller-0.7.1/ext/binding_of_caller  /usr/local/opt/ruby193/bin/ruby -r ./siteconf20161004-39055-1qp76kd.rb extconf.rb  creating Makefile    current directory: /usr/local/lib/ruby/gems/1.9.1/gems/binding_of_caller-0.7.1/ext/binding_of_caller  make  clean    current directory: /usr/local/lib/ruby/gems/1.9.1/gems/binding_of_caller-0.7.1/ext/binding_of_caller  make  compiling binding_of_caller.c  In file included from binding_of_caller.c:4:  In file included from ./ruby_headers/193/vm_core.h:30:  ./ruby_headers/193/thread_pthread.h:24:5: error: unknown type name 'clockid_t'; did you mean 'clock_t'?      clockid_t clockid;      ^~~~~~~~~      clock_t  /usr/include/sys/_types/_clock_t.h:30:33: note: 'clock_t' declared here  typedef __darwin_clock_t        clock_t;                                  ^  binding_of_caller.c:68:3: warning: suggest braces around initialization of subobject [-Wmissing-braces]    binding_mark,    ^~~~~~~~~~~~~  binding_of_caller.c:83:23: warning: shifting a negative signed value is undefined [-Wshift-negative-value]    return (cfp->flag & VM_FRAME_MAGIC_MASK) == VM_FRAME_MAGIC_IFUNC;                        ^~~~~~~~~~~~~~~~~~~  ./ruby_headers/193/vm_core.h:582:36: note: expanded from macro 'VM_FRAME_MAGIC_MASK'  #define VM_FRAME_MAGIC_MASK   (~(~0<<VM_FRAME_MAGIC_MASK_BITS))                                   ~~^  binding_of_caller.c:108:18: warning: shifting a negative signed value is undefined [-Wshift-negative-value]    switch (flag & VM_FRAME_MAGIC_MASK) {                   ^~~~~~~~~~~~~~~~~~~  ./ruby_headers/193/vm_core.h:582:36: note: expanded from macro 'VM_FRAME_MAGIC_MASK'  #define VM_FRAME_MAGIC_MASK   (~(~0<<VM_FRAME_MAGIC_MASK_BITS))                                   ~~^  3 warnings and 1 error generated.  make: *** [binding_of_caller.o] Error 1    make failed, exit code 2    Gem files will remain installed in /usr/local/lib/ruby/gems/1.9.1/gems/binding_of_caller-0.7.1 for inspection.  Results logged to /usr/local/lib/ruby/gems/1.9.1/extensions/x86_64-darwin-15/1.9.1/binding_of_caller-0.7.1/gem_make.out  

Loading table into an array constant

Posted: 04 Oct 2016 07:32 AM PDT

I have a Rails App that's essentially an invoicing and payment system. Within the application i have 2 tables that hold the misc_charges codes and description (ie: id:1 , code: '01' desc:'Apples' , id:2 , code :'02' , desc: 'Bananas' etc. ) the other table is the credits (ie: id:1 , code: '30' , desc: 'Coupon' , id:2 , code: '31' , desc: 'AAA rebate' etc). These codes are not subject to change very much and we are likely to add codes rather than modify or delete any of them.

Currently, we store the alphanumeric code in the main transaction table. such as '01' , '02' , '30' or '31'. I could have used the id generated by rails/postgresql but the reason why we use the alpha codes is because this data will eventually need to be exported and imported into another system that uses those alphanumeric codes as the primary identifier for the misc charges and credits.

Anyhow, currently in the app, when a user (or an admin) reviews their transaction history or a specific invoice, using the transaction table i get the specific description for an alphanumeric code using a model method.

class MiscCharge < ActiveRecord::Base    def self.get_desc(r_code)      result = MiscCharge.select("misc_charges_desc").where("code = ?", r_code)     return result[0].misc_charges_desc    end  end  

Then in the view i use this:

<td>    <%if p.type == "R"%>      <h5 align ="left"><%=MiscCharge.get_desc(p.code)%></h5>    <% else %>         <h5 align ="left"><%=Credit.get_desc(p.code)%></h5>    <% end %>  </td>  

Currently, the application is in development mode and we're doing some testing in a staging environment. We don't have a whole lot of transactions but i can't help but to think that calling the model to show the description for every code is bound to create some performance issues when the transaction count skyrockets or we have multiple users using the App at the same time.

Is there a way to load those codes and descriptions, which will essentially be static most of the time, into an array as a constant? I have seen articles about Ruby on Rails constants that you can define in the application.rb or in the initializers folder but the example i have seen are mostly for static data... not something loaded from a table... Are the models available to pull data from in the application.rb or initializers?

Can it be as simple as doing this

misc_charges_array = MiscCharge.select(:id, :code, :desc).map {|e| e.attributes.values}  

or is there something more to it?

Once i have that in an array, how do i go about replacing the Model method call in the view to snatch the proper description?

How do I move objects from one controller to another in Rails?

Posted: 04 Oct 2016 07:06 AM PDT

What I building is a nifty booking system where I want to move objects say "Orders" when booked by user to "BookedController" I first implemented using sessions but it is limited to a session so I basically was thinking of an "Order" with the UserID who booked it and display it on that basis but I couldn't figure how.

What I tried was sorting in categories, like New, Booked & Completed making them work like Flags but when user hits Booked, how do I change from New to Book and Associate with the UserID?

So I thought of this way of creating a completely new controller and adding User_ID of person who hits book and showing the orders based on users but I don't think either of these are good ways to do it?

Parse remote csv on Rails 4

Posted: 04 Oct 2016 06:50 AM PDT

I keep getting the error file name is too long. I am running rails on Heroku so I am trying to have an uploaded file saved on cloud, and then imported so it is not lost on their dyno.

I want to create a new object for each row in the csv. Parsing the CSV has worked perfectly before in development when using a temp file. But I have to change this for Heroku.

What is wrong about my code for the remote csv being parsed correctly?

def self.import_open_order(file_url)        open(file_url) do |file|        CSV.parse(self.parse_headers(file.read), headers: true) do |row|  ...  

How to upload file in nested parameter using CURL

Posted: 04 Oct 2016 06:44 AM PDT

I can upload single file using the following command.

curl -X POST http://localhost:3000/<valida_url>  -F "filedata=@<file_path>" -H "Content-Type: multipart/form-data" -H "Authorization:<auth_code>"  

But I need to send multiple images in nested parameter. like

{ list_of_images:{user_images: [<Here array of images>]}}

How should i form CURL command?

How to set height of a row in xlsx sheet based on content?

Posted: 04 Oct 2016 06:30 AM PDT

I am using rails "acts_as_xlsx" gem for generating reports.I want to set the height of row automatically based on content.

Here i am setting default height

sheet.add_row [id,category, @sub_category_val,priority,description,comments,client_comments,status],:style => @style,:height=>250  

Here problem is the content in "description" field may vary.So,based on the content i want to set the height of a row.Is it possible?

Thanks

Using the one-liner syntax for controller specs

Posted: 04 Oct 2016 07:00 AM PDT

I'm trying to write terse tests for an API controller, but I'm having trouble with the "one-liner" syntax offered by RSpec.

I'm overriding the subject explictly to refer to the action of posting rather than the controller:

let (:params) { some_valid_params_here }  subject { post :create, params }  

When I use the one-liner syntax to test http_status, it works fine:

it { is_expected.to have_http_status(:created) }  # pass!  

But when I try to use it for a different expectation, it blows up:

it { is_expected.to change{SomeActiveRecordModel.count}.by(1) }  # fail! "expected result to have changed by 1, but was not given a block"  

Notably, when I run this second expectation in a longer form, calling on subject explictly, it works:

it "creates a model" do    expect{ subject }.to change{SomeActiveRecordModel.count}.by(1)  end  # pass  

Is this just a weakness of the one-liner syntax, that it can't handle this more complicated expression? Or have I misunderstood something about how subject is inferred into these tests?

(NB: I know that setting the subject to an action has some detractors, and I'm happy to hear opinions, but that isn't the aim of this question).

ActionController::InvalidAuthenticityToken rails 5

Posted: 04 Oct 2016 07:33 AM PDT

I'm using rails version - 5.0.0.1

I used form_for to create a form

<%= form_for :session,:action => '/login/authenicate/',:remote => true, :authenticity_token => true, :html => { :class => 'validate', :id => 'form_login' } do |s| %>  

I am using ajax to send the request to the server.

This is the form that is displayed in the browser.

<form class="validate" id="form_login" action="/login" accept-charset="UTF-8" data-remote="true" method="post" novalidate="novalidate"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="i3GVfaN2PbZ80JvdSqO921GuNLaxxo9ctsTBE21aYJYo/XtBG7lyqU7xAzoFjClwOGWSCrC+6mf3no39ua+rDQ==">              <div class="form-group">                  <div class="input-group">                      <div class="input-group-addon">                          <i class="fa fa-user" aria-hidden="true"></i>                      </div>                      <input class="form-control" id="username" placeholder="Email Id / Mobile No" type="text" name="session[username]">                  </div>              </div>                <div class="form-group">                  <div class="input-group">                      <div class="input-group-addon">                          <i class="fa fa-lock" aria-hidden="true"></i>                      </div>                      <input class="form-control" id="password" placeholder="Passowrd" type="password" name="session[password]">                  </div>              </div>                <div class="form-group">                  <button name="authenicatebtn" type="submit" class="btn btn-primary btn-block btn-login">Login</button>              </div>  

It is a ajax request to the server when i view in the networks tab its showing ActionController::InvalidAuthenticityToken error.

Limit number of Associations based on their value

Posted: 04 Oct 2016 07:23 AM PDT

I'm fairly new to this, so apologies in advance if this is a dumb question, or if I should be approaching this in a different way. I'm certainly open to almost all suggestions!

I'm working on creating a Jeopardy backend API using Rails 4. Currently, I've seeded my database with about 100 or so Categories, and each Category has multiple Clues, which house the question, answer and value. I also have a Game model which, when created, randomly selects up to 5 Categories and their clues.

My issue is that I want to know if there is a way to make sure that each Game only has five clues, and no duplicating values (ie, I don't want 5 clues that are all worth $100). I'm not sure if this is possible to do on the backend or if I should just filter it out on the frontend (I'm not using any Views - I'm building a separate dedicated JS client that will use AJAX to get the data from the API), but I feel like there has to be a Rails way to do this!

I'm not using any Join tables - Clues belongs_to Categories, and Categories has_many Clues, then a Game has_many Categories, so it's a pretty straight tree structure. I'm not sure what code would be helpful here for reference, since my Category and Clue models are pretty bare-bones at the moment, but here is what my Game model looks like:

class Game < ActiveRecord::Base    after_create :assign_category_ids, :create_response, :reset_clues    has_many :categories    has_one :response, as: :user_input    belongs_to :user      # On creation of a new game, picks a user-specified     # number of random categories    # and updates their game_ids to match this current game id    def assign_category_ids      game_id = id      num_cats = num_categories.to_i      @categories = Category.where(id: Category.pluck(:id).sample(num_cats))      @categories.map { |cat| cat.game_id = game_id }      @categories.each(&:save)    end      # Creates response to calculate user answer    def create_response      build_response(game_id: id, user_id: user_id)    end     # Resets categories and clues on every new game    def reset_clues      @categories = Category.where(game_id: id)      @categories.each do |category|        category.clues.each { |clue| clue.update_attributes(answered: false) }        category.update_attributes(complete: false)      end    end  end  

Any advice at all will be greatly appreciated!! Thank you in advance!

ruby JSON.pretty_generate() doesn't work

Posted: 04 Oct 2016 05:38 AM PDT

I'm trying to print JSON data in a view in a 'pretty' human readable format. I have a controller:

def show    h = JSON.parse(RestClient.get("http://link_to_get_json"))    @json = JSON.pretty_generate(h)  end  

and a simple view:

= @json  

But all I see, when I load the page, is the same JSON I've got, not formatted. What do I do wrong?

paypal payouts resulted denied status

Posted: 04 Oct 2016 05:31 AM PDT

I have created a US based paypal account and a block of code for paypal payouts but it resulted denied status.

"errors":{"name":"ACCOUNT_UNCONFIRMED_EMAIL ","message":"Sender's email is not confirmed","information_link":"https://developer.paypal.com/docs/api/payments.payouts-batch/#errors"}  

paypal accounts email is confirmed but the senders sandbox account seems to unverified and could not find any way there to confirm it.

Could anyone help me on this.

Regards, Sreeraj

Rails - how to correctly implement a payment/booking process

Posted: 04 Oct 2016 07:26 AM PDT

I'm building an events app in rails and I'm using Stripe to collect my payments. It took me a while but I've got payments working. However, when I try and increase the quantity of spaces to book, the system will only take one payment. So if an event is £10 per 'space' and someone wants to book 5 spaces, regardless of the fact the payments form states the correct amount (£50 in this example), only £10 is collected. I'm pretty sure this is an MVC issue but can't seem to spot how to resolve it. In my views I have the following code -

bookings.new.html.erb

    <div class="col-md-6 col-md-offset-3" id="eventshow">    <div class="row">      <div class="panel panel-default">          <div class="panel-heading">              <h2>Confirm Your Booking</h2>          </div>                    <div class="calculate-total">                                <p>                                    Confirm number of spaces you wish to book here:                                      <input type="number" placeholder="1"  min="1" value="1" class="num-spaces">                                </p>                                  <p>                                      Total Amount                                      £<span class="total" data-unit-cost="<%= @event.price %>">0</span>                                  </p>                            </div>                            <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %>                         <span class="payment-errors"></span>                    <div class="form-row">                      <label>                        <span>Card Number</span>                        <input type="text" size="20" data-stripe="number"/>                      </label>                  </div>                    <div class="form-row">                    <label>                    <span>CVC</span>                    <input type="text" size="4" data-stripe="cvc"/>                    </label>                  </div>                    <div class="form-row">                      <label>                          <span>Expiration (MM/YYYY)</span>                          <input type="text" size="2" data-stripe="exp-month"/>                      </label>                      <span> / </span>                      <input type="text" size="4" data-stripe="exp-year"/>                  </div>              </div>              <div class="panel-footer">                       <%= form.button :submit %>                  </div>     <% end %>  <% end %>          </div>    </div>  </div>      <script type="text/javascript">      $('.calculate-total input').on('keyup change', calculateBookingPrice);    function calculateBookingPrice() {    var unitCost = parseFloat($('.calculate-total .total').data('unit-cost')),        numSpaces = parseInt($('.calculate-total .num-spaces').val()),        total = (numSpaces * unitCost).toFixed(2);      if (isNaN(total)) {      total = 0;    }      $('.calculate-total span.total').text(total);  }      $(document).ready(calculateBookingPrice)    </script>        <script type="text/javascript" src="https://js.stripe.com/v2/"></script>    (code for stripe)  

This works fine on the actual payments page as the example below shows -

Payment form with quantity function

So, for this example I've used an @event.price of £1 per space/booking. However, if I go ahead and process this booking, rather than £3 that is collected by Stripe, it only shows as £1.

I think this may have to do with the fact @event.price is what I'm expressing in my views, however,when I replace @event.price with @booking.total_amount I then only get the total amount in my payment form (as above) showing as zero and regardless of what I do with the quantity function it stays at zero.

As you can see from the views code my quantity function is handled with some javascript. Am I missing something from this function to make this work?

Do I have the correct params in my controller? Here's my controller code -

bookings_controller.rb

     class BookingsController < ApplicationController        before_action :authenticate_user!        def new          # booking form          # I need to find the event that we're making a booking on          @event = Event.find(params[:event_id])          # and because the event "has_many :bookings"          @booking = @event.bookings.new(quantity: params[:quantity])          # which person is booking the event?          @booking.user = current_user          #@total_amount = @event.price * @booking.quantity          end        def create            # actually process the booking          @event = Event.find(params[:event_id])          @booking = @event.bookings.new(booking_params)          @booking.user = current_user                if                   @booking.reserve                  flash[:success] = "Your place on our event has been booked"                  redirect_to event_path(@event)              else                  flash[:error] = "Booking unsuccessful"                  render "new"              end      end          private        def booking_params          params.require(:booking).permit(:stripe_token, :quantity, :event_id, :stripe_charge_id, :total_amount)      end        end  

Here's my model code with validations -

Booking.rb

     class Booking < ActiveRecord::Base        belongs_to :event      belongs_to :user          validates :total_amount, presence: true, numericality: { greater_than: 0 }      validates :quantity, :total_amount, presence: true        def reserve          # Don't process this booking if it isn't valid          self.valid?                        # Free events don't need to do anything special                  if event.is_free?                  save!                    # Paid events should charge the customer's card                  else                        begin                          self.total_amount = event.price * self.quantity                          charge = Stripe::Charge.create(                              amount: total_amount * 100,                              currency: "gbp",                              source: stripe_token,                               description: "Booking created for amount #{total_amount}")                          self.stripe_charge_id = charge.id                          save!                      rescue Stripe::CardError => e                      errors.add(:base, e.message)                      false                  end              end         end  end  

This has had me stumped for a while. I'm pretty new to Rails so feel sure a more experienced eye can spot where I'm going wrong. Any guidance is appreciated.

ActiveAdmin: Not saving association between my two models

Posted: 04 Oct 2016 04:53 AM PDT

How can the association between my two models be saved in ActiveAdmin?

I have two models a room and a photo model. In the ActiveAdmin I want to update the association between the photo and the room.

room.rb (app/models)

class Room < ApplicationRecord      has_many :photos      accepts_nested_attributes_for :photos  end  

photo.rb (app/models)

class Photo < ApplicationRecord    belongs_to :room      has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/  end  

photo.rb (app/admin)

   ActiveAdmin.register Photo do     permit_params :image, :room_id, :listing_name       index do      selectable_column      id_column      column :image_file_name      column :listing_name      column :room      column :updated_at      column :created_at      actions    end       show do |image|        attributes_table do           row :image do              photo.image? ? image_tag(photo.image.url, height: '100') : content_tag(:span, "No photo yet")           end        end        active_admin_comments     end       form :html => { :enctype => "multipart/form-data" } do |f|        f.inputs do           f.input :image, hint: f.photo.image? ? image_tag(f.photo.image.url, height: '100') : content_tag(:span, "Upload JPG/PNG/GIF image")           f.collection_select :room, Room.all,:id,:listing_name         end        f.actions     end   end  

The form seems to work but it does not save it to the database when I check the record(last room) in the rails console it always returns me room_id: nil? I have tried everything nothing seems to work. Please help.

Store uploaded images tdefinitely based on their json representation

Posted: 04 Oct 2016 04:45 AM PDT

Hello everyone since the past hour i've been trying to use minimagick gem, but i can't figure out why i can't open an image. the return value is always null

i have the following code in my controller:

class UploadController < ApplicationController      require 'mini_magick'        def load          file = "public/uploads/cache/img.jpg"          image = MiniMagick::Image.open(file)          render json: image      end  end  

On a get to upload#load i get a null value.

i have installed minimagick on my mac using homebrew. i restarted the server.

Thanks!

Partial Pivoting in PostgreSQL or Rails

Posted: 04 Oct 2016 04:42 AM PDT

Assume I have 3 tables, and I can't change any DDL

Class  id: integer  name: string  

and

Student  id: integer  name: string  class_id: integer //Foreign key to Class table  

and

Score  id: integer  student_id: integer //Foreign key to Student table  subject: string //String enum of "Math", "Physics", "Chemistry"  score: float  

Also, assume that the string enum will always correct, filled by only one of those three possible values.

And I need a resulting query like this student_id | student_name | class_name | math | physics | chemistry where math field is the average score of "Math" subject, physics field is the average score of "Physics" subject, and chemistry field is the average score of "Chemistry" subject of the student with id student_id.

I know that I can handle it in Rails ActiveRecord::Base, but even using include, I end up with using many queries.

How can I generate that needed output with using only one query?

Images are not properly stored in temp folder in Apache where working fine in Rails production mode

Posted: 04 Oct 2016 03:58 AM PDT

I am using IMGKit for generating screenshots. According to the code, I am taking a screenshot of a particular page / url as mentioned and then storing this in a path. When I upload new image, the image is overriden with same filename which is right. This is working fine in RAILS_ENV=production but when I try to run this in Apache, it is showing the same image all the time irrespective of the url. Please help.

def upload    url = "http://xxx.xxx.xx.xx/" + "users/#{@user_id}/reports/#{@report_id}"    kit = IMGKit.new(url)    file_path = 'public/images/myimage.jpg'    file = kit.to_file(file_path)    -----------------------------------------------  end  

how to pause/resume of file during uploading on server in rails

Posted: 04 Oct 2016 03:58 AM PDT

i want to make a resume able video up loader in rails . what is the best way to make this .should i use to fineuploadr , or jquery-file-uploader.

is it possibale with paperclip gem ruby or not ? I tried it with jquery file uploader plugin . here is my _form.

<script>  $(document).ready(function(){    $("#video_file").bind('change', function() {      console.log(this.files[0].size);    });      $("#submit-upl").click(function(){      $('#new_video').fileupload({        maxNumberOfFiles: 1,        maxChunkSize: 10000000, // 10 MB        type: 'PATCH',        add: function (e, data) {          var that = this;          $.getJSON(resume_path, { file: data.files[0].name }, function (result) {              var file = result.file;              data.uploadedBytes = file && file.size;              $.blueimp.fileupload.prototype                  .options.add.call(that, e, data);          });        }     });    })         })  </script>
<%= form_for video , method: :post , :multipart => true do |f| %>    <% if video.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(video.errors.count, "error") %> prohibited this video from being saved:</h2>        <ul>        <% video.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>    <div class="field">      <%= f.label :file %>      <%= f.file_field :file %>    </div>    <div class="actions">      <%= f.submit "save" , id: "submit-upl" %>    </div>  <% end %>

 def create  @video = Video.new(video_params)  file = params[:video][:file]    File.open(Rails.root.join('app','assets', 'images', file.original_filename), 'ab') do |f|      f.write(file.read)    end      @video.file =  file.original_filename  respond_to do |format|    if @video.save      format.html { redirect_to @video, notice: 'Video was successfully created.' }      format.json { render :show, status: :created, location: @video }    else      format.html { render :new }      format.json { render json: @video.errors, status: :unprocessable_entity }    end  end  

end

LoadError: cannot load such file — capistrano/rbenv (2)

Posted: 04 Oct 2016 03:52 AM PDT

This is almost the same question as here: LoadError: cannot load such file -- capistrano/rbenv

I experience the same problem as described there but neither solution does work.

I thoroughly followed the instruction at https://gorails.com/deploy/ubuntu/16.04 - but it did not work.

My question is: if I want to set up rbenv on a remote computer - do I have to have rbenv on my local computer - where I run cap production deploy?

I currently have RVM on my local computer - but want to set up rbenv on a remote one. Perhaps it's not possible and I must firstly replace RVM on the local computer to rbenv?

Ruby on Rails console --help not working

Posted: 04 Oct 2016 03:44 AM PDT

I have rails 5 installed via rvm, and when I type rails -h or rails generate model -h etc, I only get the standard help message :

 $ rails generate model -h  Usage:   rails new APP_PATH [options] ...  

I should be able to get help with all of the different rails commands on the console. Any suggestions?

Thanks.

Get set of hashes from array of hashes between two date values

Posted: 04 Oct 2016 03:49 AM PDT

I have an array of hashes that contains a date and total key.

For example:

hash = [{    "Date"=>"01/01/2016",    "Total"=>10  },{    "Date"=>"02/01/2016",    "Total"=>20  },{    "Date"=>"03/01/2016",    "Total"=>30  },{    "Date"=>"04/01/2016",    "Total"=>40  },{    "Date"=>"05/01/2016",    "Total"=>50  }]  

What I want to do is pass two dates to a method that then returns only hashes whose dates are either matching or between the two dates.

So for example:

get_data(startDate, endDate)    end  

Where the startDate and endDate are '02/01/206' and 04/01/2016

Would return:

{    "Date"=>"02/01/2016",    "Total"=>20  },{    "Date"=>"03/01/2016",    "Total"=>30  },{    "Date"=>"04/01/2016",    "Total"=>40  }  

Quickbook Create invoice error in rails

Posted: 04 Oct 2016 07:07 AM PDT

i am getting this error when i am creating invoice using Quickbook rails gem (quickbooks-ruby)

Quickbooks::IntuitRequestException (Required param missing, need to supply the required value for the API:      Required parameter Line.DetailType is missing in the request):    app/controllers/users_controller.rb:42:in `oauth_callback'  

My Controller

    class UsersController < ApplicationController        def index          upload_service = Quickbooks::Service::Upload.new          # result = upload_service.upload("tmp/monkey.jpg", "image/jpeg", attachable_metadata)        end          def authenticate          callback = users_oauth_callback_url          token = QB_OAUTH_CONSUMER.get_request_token(:oauth_callback => callback)          session[:qb_request_token] = Marshal.dump(token)          redirect_to("https://appcenter.intuit.com/Connect/Begin?oauth_token=#{token.token}") and return        end          def oauth_callback          at = Marshal.load(session[:qb_request_token]).get_access_token(:oauth_verifier => params[:oauth_verifier])          session[:token] = at.token          session[:secret] = at.secret          session[:realm_id] = params['realmId']       end         def create_invoice          access_token = OAuth::AccessToken.new(QB_OAUTH_CONSUMER, session[:token], session[:secret] )          invoice = Quickbooks::Model::Invoice.new          invoice.customer_id = 123          invoice.txn_date = Date.civil(2013, 11, 20)          invoice.doc_number = "1001" # my custom Invoice # - can leave blank to have Intuit auto-generate it          line_item = Quickbooks::Model::InvoiceLineItem.new          line_item.amount = 50          line_item.description = "Plush Baby Doll"          line_item.sales_item! do |detail|            detail.unit_price = 50            detail.quantity = 1            detail.item_id = 500 # Item ID here          end            invoice.line_items << line_item          service = Quickbooks::Service::Invoice.new          service.company_id = session[:realm_id]          service.access_token = access_token          created_invoice = service.create(invoice)          puts created_invoice.id          redirect_to root_url        end      end  

config/initializers/quickeebooks.rb

OAUTH_CONSUMER_KEY = "xxxxxxxxxxxxxxxxxxxxxxx"  OAUTH_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"    ::QB_OAUTH_CONSUMER = OAuth::Consumer.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, {      :site                 => "https://oauth.intuit.com",      :request_token_path   => "/oauth/v1/get_request_token",      :authorize_url        => "https://appcenter.intuit.com/Connect/Begin",      :access_token_path    => "/oauth/v1/get_access_token"  })  

how to add rows dynamically in ruby on rails with jquery?

Posted: 04 Oct 2016 03:44 AM PDT

Application contains invoice line item. While creating new invoice, I need to add rows dynamically in table contains information regarding product name, description, and product unit cost.

I have a "Add" button, when user press this button one row will be added in the form.

Code from new.html.erb in which i have created table body.

 <tbody>    <%= simple_form_for(@invoice) do |f| %>      <%= f.error_notification %>      <tr id='row0'>        <%= f.fields_for :products do | product | %>          <td><%= product.input :product_name, placeholder: 'Product Name', label: false %></td>          <td><%= product.input :product_description, placeholder: 'Product Description', label: false %></td>          <td><%= product.input :product_price, placeholder: 'Product Unit Cost', label: false %></td>          <% end %>               <td><button id="add_row" type="button" class="btn btn-primary">Add</button></td>      </tr>      <tr id='row1'></tr>    <% end %>  </tbody>  

now I need solution to add rows dynamically via jquery. So for that I tried following code.

but failed to generate output...invoice_item.js is as follows

$(document).ready(function(){    var i=1;    $("#add_row").click(function(){      $('#row'+i).html("<td><%= product.input :product_name, placeholder: 'Product Name', label: false %></td><td><%= product.input :product_description, placeholder: 'Product Description', label: false %></td><td><%= product.input :product_price, placeholder: 'Product Unit Cost', label: false %></td>");      $('#invoice_table').append('<tr id="row'+(i+1)+'"></tr>');      i++;       });  });  

if I wanted to append the new.html.erb code to the page using jquery, what is the best way?

Can't start my postgres server

Posted: 04 Oct 2016 03:11 AM PDT

When I try to launch my psql server, I receive a postgres popup saying:

There is already a PostgreSQL server running on port 5432. Please stop this server before starting Postres.app. If you want to use multiple servers, configure them to use different ports.

To give a little bit of a context, I've killed all my postgres connection with the following command:

select pg_terminate_backend(pid) from pg_stat_activity where datname='YourDatabase';  

as I wasn't able to rake db:reset my db.

Problem is that now that I can't use postgres on any of my apps.

Issue in mobile device in the ajax call remote option

Posted: 04 Oct 2016 03:00 AM PDT

In rails, I am using the same code to get js response and render UI according to the response . My code is like this

= link_to "Click here", :page=>(@page+1).to_s, :remote => true  

But in the computer browser, it is generating js response while in mobile browser is generating html response

In computer it is getting the server log

 Processing by DemoController#list as js  

While browsing in mobile it produces the log

Processing by DemoController#list as html  

I want js reponse in mobile devise as well. What may be the issue? Please help me to solve . Thanks in advance

Loop through array of hashes in rails

Posted: 04 Oct 2016 03:07 AM PDT

I have the following array of hashes that I send to my controller:

comparisons = [{    "startdate": "01/01/2016",    "enddate": "01/02/2016"  }, {    "startdate": "01/03/2016",    "enddate": "01/04/2016"  }, {    "startdate": "01/05/2016",    "enddate": "01/06/2016"  }, {    "startdate": "01/05/2016",    "enddate": "01/06/2016"  }];    $.ajax({    url: '/get_data',    method: 'GET',    dataType: 'JSON',    data: {      startdate: '01/01/2016',      enddate: '01/01/2016',      comparisons: comparisons    },    success: function (data) {      console.log(data);    }  });  

And then in the controller I want to loop through these comparisons:

@comparisons = []  if !params[:comparisons].blank?    params[:comparisons].each do |c|      @comparisons.push({:startdate => c[:startdate], :enddate => c[:enddate], :data => get_data(c[:startdate], c[:enddate], 'week')})    end  end  

I get an error: > no implicit conversion of Symbol into Integer

And when debugging I'm finding that the c in my loop isn't structured the same as what I'm sending...

c: ["0", {"startdate"=>"01/01/2016", "enddate"=>"01/01/2016"}]

How can I fix this?

Creating Filter Form in Views

Posted: 04 Oct 2016 05:52 AM PDT

So i am trying to filter the data that is presented in my Index action by using scope.

I have defined it as so in profile.rb

scope :fees_to, -> (fees_to) { where("fees_to <= ?", "#{fees_to}") }  

It works perfectly fine in rails console, i can do Profile.fees_to(50) for example and it returns all profiles that has fees_to that are less than 50.

What i would like to know is how do i create this input filter method in my index views?

In profiles_controller.rb for Index action, the code is as follows:

def index    @profiles = Profile.where(nil)    @profiles = @profiles.fees_to(params[:fees_to]) if params[:fees_to].present?  end  

I've tried collecting the information in my index view in various ways, all to know avail.

Any help or advice would be greatly appreciated. Thanks!

How to create a method in rails which executes automatically at a given time

Posted: 04 Oct 2016 02:31 AM PDT

I want to create a method which contains email function.But i need to run a scheduler at 12:00am daily.Which should check from employee table whether there are any Birthday of any specific employee related to that specific date.If it founds an Birthday then it should send an greeting to the employee using rails Action Mailer.It is possible if i take button and when i click on it then email should be gone,but i want this automatically without any onclick event.So pls help by providing an Example for this.

How to hit the api that runs on ubuntu inside virtualbox?

Posted: 04 Oct 2016 02:36 AM PDT

i'm facing difficulties to hit the api runs on ubuntu inside virtualbox. virtualbox's ip address is 10.0.2.15 . when im trying to hit this ip, i cant access it.

so help me to hit the rails api, that runs on port 3000

TIA

Error session-1::#<Net::SSH::Connection::Session:0x2cfc238>

Posted: 04 Oct 2016 04:17 AM PDT

While i was running one of my ruby script it is throwing error like

"session-1::#".And it is continuoesly in the loop only.

No comments:

Post a Comment