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.

Monday, October 3, 2016

Why can't I get /comments/new.html.erb? | Fixed issues

Why can't I get /comments/new.html.erb? | Fixed issues


Why can't I get /comments/new.html.erb?

Posted: 03 Oct 2016 08:04 AM PDT

I created models by scaffold command

class Post < ActiveRecord::Base    has_many :comments, as: :commentable  end    class Comment < ActiveRecord::Base    belongs_to :commentable , polymorphic: true  end    ...  

routes.rb:

 resources :posts, :images, :links do      resources :comments   end  

comments_controller.rb:

def new    @comment = Comments.new  end  

/posts/show.html.erb:

 <%= link_to 'Add comment', new_post_comment_path (@post)%>  

Here I think I need ...(@post, @comment),like from http://guides.rubyonrails.org/routing.html:

<%= link_to 'Ad details', magazine_ad_path(@magazine, @ad) %>  

but I haven't @comment here.

I get error:

    Showing /home/loza/Projects/my_blog/app/views/comments/_form.html.erb where line #1 raised:        undefined method `comments_path' for #<#<Class:0x007f2e4a77c2f0>:0x007f2e4ab23ef8>    Extracted source (around line #1):   <%= form_for(@comment) do |f| %>    <% if @comment.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>          <ul>  

How need I write so as to get /comments/new.html.erb?

call method of a controller from different controller view

Posted: 03 Oct 2016 08:16 AM PDT

The idea that when the user filling the booking info, he need to verify his phone number in the form where he receive the code and put it with rest of booking info before submitting , so I have the following view

<%= form_for(@booking) do |f| %>      <%= current_or_not_authenticated_user.email %>      <br>      <%= f.label :patient_id %>      <%= f.collection_select :patient_id, User.order(:created_at), :id, :email %>      <button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#patientModal">        New Patient      </button>      <br>      <div class="form-group">        <%= f.label :type %>        <%= f.select :booking_type, options_for_select([['Physiologist'], ['Psychiatrist'], ['Pediatrician']]) %>        <%= f.hidden_field :customer_id, :value => current_or_not_authenticated_user.id %>      </div>      <div class="form-group">        <%= f.label :address %>        <%= f.collection_select :address_id, Address.where(user_id: current_or_not_authenticated_user.id), :id, :address1 %>        <button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#addressModal">          New Address        </button>        <% if current_user && !current_user[:verified_by_phone_at]   %>            <div class="form-group">              <%= label_tag(:phone) %>              <%= text_field_tag(:phone) %>              <button id="smsBtn" type="button" class="btn btn-primary">Send SMS</button>            </div>            <div class="form-group">              <%= label_tag :code %>              <%= text_field_tag :code %>            </div>        <% end %>        <%= f.submit "Confirm Booking" %>      </div>      <br>  <% end %>          <script>        $(document).ready(function () {          $('#smsBtn').on('click', function () {            $.ajax({              url: <%=phone_verification_index_path %>,              type: 'ajax',              data: $('#code').val()            });            });          });        </script>  

clicking on smsbtn should go to phone_verification controller which in turn call third party method that send sms to the user, then the user fill his code and click on submit.

my problem is when the user click on smsbtn, the @booking form get submitted and I don't want to form submit unless the user click on Confirm Booking, the only way that my jquery was working, was when I moved both phone field and smsbtn outside form.

the order of the fields is important because I don't want the user to find code field first then phone field under it.

fill a JSON file with embedded arrays from Rails

Posted: 03 Oct 2016 07:24 AM PDT

I have a simple table indexed by an id. I would like to have a structured JSON that group each user from a family in an array structure. And then each family in a global array. How can I do that ?

my plain code :

json.rss @rss do |rs|    json.id rs.id    json.name rs.name    json.family rs.family    json.lastdate rs.lastdate    json.last rs.last    json.s1w rs.s1w    json.s2w rs.s2w      json.s1m rs.s1m      json.s2m rs.s2m      json.s3m rs.s3m    json.s6m rs.s6m    json.ytd rs.ytd  end  

Collecting text submitted in input field with ember-rails

Posted: 03 Oct 2016 07:27 AM PDT

I am following an ember-rails tutorial. It's using coffeescript and I'm writing in javascript. Essentially I have a form that when I submit text on it it should place the text below.

My controller looks like this:

Emberapp.ApplicationController = Ember.Controller.extend({      entries: [],    actions: {      addEntry: function(){        this.entries.pushObject name: this.get('newEntryName');        this.set('newEntryName', "");      }    }  });  

My template looks like this

<div id = "container">    <h1>Emberails</h1>      {{ input value=newEntryName enter='addEntry' }}      <ul>      {{#each entries}}        <li>{{name}}</li>      {{/each}}    </ul>    </div>  

When I reload the page I get an error stating that 'name: this.get('newEntryName');' is an Unexpected identifier. I've been checking for the syntax rules online but I'm not sure if it is a coffeescript to javascript error or something else.

What is the purpose of the "system" folder in rails "public/system/"?

Posted: 03 Oct 2016 07:05 AM PDT

The standard place to store non-precompiled public assets in a rails app is in "public/system." Is there any reason for this? I'd like to keep things simple, why shouldn't I just put assets in the "public" folder?

Creating model and nested model (1:n) at once with ActiveRecord

Posted: 03 Oct 2016 06:54 AM PDT

My Rails5 application has an organization model and a user model (1:n relationship). The workflow of creating an organization should include the creation of the organization's first user as well. I thought this would be able with ActiveRecord through nested models, however the create action fails with the error message "Users organization must exist".

class Organization < ApplicationRecord      has_many :users, dependent: :destroy      accepts_nested_attributes_for :users  end    class User < ApplicationRecord      belongs_to :organization  end    class OrganizationsController < ApplicationController      def new          @organization = Organization.new          @organization.users.build      end        def create          @organization = Organization.new(organization_params)          if @organization.save              redirect_to @organization          else            render 'new'          end      end        def organization_params          params.require(:organization).permit(:name, users_attributes: [:name, :email, :password, :password_confirmation])      end  end  

In the view I use the <%= f.fields_for :users do |user_form| %> helper.

Is this a bug on my side, or isn't this supported by ActiveRecord at all? Couldn't find anything about it in the rails guides. After all, this should be (theoretically) possible: First do the INSERT for the organization, then the INSERT of the user (the order matters, to know the id of the organization for the foreign key of the user).

Destroy functionality not working in ToDo app . Editing works just fine

Posted: 03 Oct 2016 06:49 AM PDT

I am making a basic ToDo app and have lost functionality to destroy (delete) a task after I create it. There are two buttons on the app so far, edit, and delete. The edit button is fully functional. I can't seem to figure out where I went wrong. A click on the delete button does not even prompt a dialog box to come up with options any longer. Any advice would be appreciated greatly.

Task.rb:

class Task < ActiveRecord::Base    validates_presence_of :title    validate :future_completed_date      private      def future_completed_date      if !completed.blank? && completed > Date.today        self.errors.add(:completed, "can't be in the future")      end    end  end  



Tasks controller:

class TasksController < ApplicationController  def new    @task = Task.new    render :show_form  end    def create    @task = Task.new(task_params)    save_task  end    def edit    @task = Task.find(params[:id])    render :show_form  end      def update    @task = Task.find(params[:id])    @task.assign_attributes(task_params)    save_task  end      def destroy      @task = Task.find(params[:id])      authorize! :destroy, @task      @task.destroy      @tasks = Task.all    end     private      def save_task      if @task.save        @tasks = Task.all        render :hide_form      else        render :show_form      end    end        def task_params      params.require(:task).permit(:title, :note, :completed)    end  end  

Redmine override application.rb and add new Initializer in plugin

Posted: 03 Oct 2016 06:37 AM PDT

I'am using a gem ntlm-sso. I want to use it in Redmine. As it is written in the instructions, I added new file in config/initializers/ntlm-sso.rb and adding the line config.middleware.use "NTLMAuthentication" to config/application.rb. It works, but I want to use it as a plugin, without changing the core code. How can I override application.rb and add new initializer as Redmine plugin?

How to use simple_form with a gem to select state/province and city one a country is selected?

Posted: 03 Oct 2016 06:32 AM PDT

I am looking to a find a solution to select in a form, based on country selected (which works well) one of the states or provinces of the selected country and once the state is selected, one of the cities in that state to be selected further.

I am looking at this gem (since others I found are not a match for Rails 5).

https://github.com/loureirorg/city-state/issues  

Or is someone else has a better solution I am looking to use it.

Sidekiq + ActionJob with ActionCable in production mode

Posted: 03 Oct 2016 07:11 AM PDT

My stack Rails 5, ActionCable, ActiveJob, Sidekiq 2.2 and Redis. In development mode all work correct. In production with Sidekiq and Redis ActiveJob doesn't work.

Source code:

#notification_channel  def execute(data)    act = data['act']    data['current_profile'] = current_profile    data['profile'] = Profile.find(data['profile']);     follow_unfollow(act, data['profile'])    NotificationJob.perform_later act, data  end      #NotificationJob  class NotificationJob < ApplicationJob    queue_as :default      def perform(type, data)      begin        #some code        ActionCable.server.broadcast "notifications_channel_#{data['profile'].id}", params      rescue => e        logger.error(e.message.red + "\n")        logger.error(e.backtrace.inspect.red + "\n")      end    end    end  

Cable configs:

#config/cable.yml  production:    adapter: redis    url: redis://localhost:6379/1  

Sidekiq Configs:

 #config/initializers/sidekiq.rb   Sidekiq.configure_server do |config|     config.redis = { :url => 'redis://localhost:6379/1', :namespace => my_namespace }   end     Sidekiq.configure_client do |config|     config.redis = { :url => 'redis://localhost:6379/1', :namespace => my_namespace }   end  

In production log I see:

#production.log  D, A LOT OF ACTIONS FROM notification_channel  I, [2016-10-03T00:00:11.535425 #8897]  INFO -- : [ActionCable] [tag] [ActiveJob] Enqueued NotificationJob (Job ID: eb93ed75-a8f3-488d-ac1a-ccd6656d2a7c) to Sidekiq(my_namespace_default) with arguments: "follow", {"act"=>"follow", ...other_params...}  

Sidekiq log contains only info about Booting, has no message about some actions.

Please help me!

rails - list of tenants to migrate appears to be empty when loading a schema

Posted: 03 Oct 2016 06:28 AM PDT

what does it mean if in rails I run db:schema:load, and the schema loads until it says that "the list of tenants to migrate appears to be empty"? And what ways are available to solve this?

As in here (sorry I am unable to format it better):

... --create_table("users", {:force=>:cascade})
-> 0.4490s -- create_table("web_migrations", {:id=>false, :force=>:cascade})
-> 0.6138s -- initialize_schema_migrations_table()
-> 0.0332s [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things:

      1. You may not have created any, in which case you can ignore this message        2. You've run `apartment:migrate` directly without loading the Rails environment          * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate`        Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this.  

If statement causing NoMethodError for new accounts

Posted: 03 Oct 2016 07:33 AM PDT

I'm working on a project where I want a user to be able make a post once a day. If the user has a post already that day then I want the UI elements for submitting a post not to show. To do this I've used:

<% if current_user.posts.last.date.past? %>   

in my html.erb file. However the problem with this is if the user has never made a post then it causes undefined method `date' for nil:NilClass error. I'm not sure what to do to fix this?

How to pluck "as alias_name" from rails active record query

Posted: 03 Oct 2016 07:47 AM PDT

I have this query:

Client.select("name as dname")  

Which is working fine.

Client.select("name as dname").first.dname  => "Google"  

Now I want to get all dnames as an array but pluck method does not work as dname is not column name.

2.2.5 :040 > Client.select("name as dname").pluck(:dname)     (0.6ms)  SELECT dname FROM "clients"  ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "dname" does not exist  

How to get array of dnames? Is there any method like pluck which works on column name alias which is defined using as.

I can do this

Client.select("name as dname").map{|d| d.dname}  

But looping through every record is not making any sense to me

Rails change ActiveJob adapter for a single job

Posted: 03 Oct 2016 05:34 AM PDT

I have some scheduled tasks that run jobs with a real queue service.

Now, I want to be able to run those tasks manually from a dashboard, wait for its execution, and read/process some of its outputs in a controller action. The typical case being when an admin wants to manually reload some statistics, and it's fine to stall the server for a couple secs.

Is there a way to change the ActiveJob adapter to "inline" in order to do that ? If possible I'd also like to read some artifacts generated by this job (could be instance variables, or the return value of the performaction).

Any way to do that ?

How do I return distinct values with options_from_collection_for_select helper?

Posted: 03 Oct 2016 06:02 AM PDT

I am trying to return the countries of my products within a select tag using

options_from_collection_for_select()  

I have a Product model, with country as a column name. My code looks like this

<%= select_tag(:country, options_from_collection_for_select(Product.all.order(:country), :id, :country), :prompt => "Alle Länder") %>  

However it gives me each country more than once in the dropdown field i.e. each country appears 20 times.

Now I've been trying to use a solution suggested in a similar question, like so

options_from_collection_for_select(Product.all.pluck('DISTINCT country'), :id, :country), :prompt => "Alle Länder") %>  

however I get an error stating:

"undefined method `country' for "Spain":String  Did you mean?  count"  

Now I cant figure out which method is appropriate in this case.

Thank you very much!

sharing session of Rails cookie store between rails and grape [duplicate]

Posted: 03 Oct 2016 05:28 AM PDT

This question is an exact duplicate of:

I want to share Rails session of cookie store between Rails and grape. I watch following ling method. https://gist.github.com/jgyllen/3862855 But I cannot share session. Do you know someone better way?

Why we are creating two different mailer view(welcome_email.text.erb and welcome_email.html.erb) for single mailer action?

Posted: 03 Oct 2016 05:16 AM PDT

Many times I have created two different formats for action mailer view templates like welcome_email.text.erb and welcome_email.html.erb. But I didn't find the proper solution for why we are creating those files?

can you please any one help me?

Sorting based on multiple submodel conditions/states

Posted: 03 Oct 2016 07:26 AM PDT

I have a Room model that has_many Intervals. Intervals has a start_date and end_date attributes. I want to order the Rooms based on the following conditions

1- Room with no intervals 2- Room with any interval(s) with start_date > Date.today 3- Room without any intervals with start_date > Date.tody

I want to sort the Rooms in such a way that Rooms satisfying 1 come first then Rooms satisfying 2 then 3 using a postgresql query not a method on the model.

While I have no problem finding out which Rooms have no intervals using the query/scope below

joins("LEFT OUTER JOIN intervals ON rooms.id = intervals.room_id").where("intervals.id is NULL")  

I am having issues ordering by the 3 conditions in a single query, I tried the following

Room.joins("LEFT OUTER JOIN intervals ON rooms.id = intervals.room_id").order("CASE WHEN intervals.id IS NULL THEN 1 END ASC")  

The issue with this query is that if you call distinct on it you get the error PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list, the other issue even when you call distinct here and it works properly you would have sorted by only one condition which is the first 1.

My idea is to generate a function with case conditional to give a value of generated column based on the 3 conditions and give the first the value 1, the second value 2, and the third value 3 and sort by this computed value, whenever I try it though I get hit by the error mentioned above. Any help would be appreciated.

This is my trial to combine all 3 conditions:

Room.joins("LEFT OUTER JOIN intervals ON rooms.id = intervals.room_id").group("room.id").order("CASE WHEN room.id IS NULL THEN 1 WHEN COUNT(CASE WHEN intervals.start_date > '#{Date.today.to_s(:db)}' THEN 1 END) > 0 THEN 2 WHEN COUNT(CASE WHEN intervals.start_date > '#{Date.today.to_s(:db)}' THEN 1 END) = 0 THEN 3 END")  

This however gives the error: PG::GroupingError: ERROR: column "intervals.id" must appear in the GROUP BY clause or be used in an aggregate function

Any help would be appreciated.

rails validate in model that value is inside array[2]

Posted: 03 Oct 2016 08:04 AM PDT

This question similar with this one, but those answers don't work for me(May be they are deprecated). I don't want to reopen old question by bounty, because I have a little different arguments. In my case i have an array like this allowed_values = [99.50..200] and I tried with:

class Thing < ActiveRecord::Base     validates :price, :inclusion=> { :in => allowed_values }  

It does not work. I have tried with so many ways by examples validation here. I have little experience on coding rails. So please, help to find solution.

More info:

       ruby version: ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]         rails version: Rails 4.1.5  

Net::SSH::AuthenticationFailed while deploying Rails 4.2.x application using capistrano 3.6.1

Posted: 03 Oct 2016 05:05 AM PDT

When I try to deploy the application with capistrano 3.6.1 and ruby 2.3.1, I get following error for Rails 4.2.x

amit@amit:~/smart-recruit$ cap production doctor  (Backtrace restricted to imported tasks)  cap aborted!  Net::SSH::AuthenticationFailed: Authentication failed for user deploy@myserver.com    Tasks: TOP => rvm:hook => passenger:rvm:hook => passenger:test_which_passenger  (See full trace by running task with --trace)  

deploy.rb

# config valid only for current version of Capistrano  lock '3.6.1'    set :application, 'smart-recruit'  set :repo_url, 'git@github.com:SomeUser/smart-recruit.git'  set :deploy_to, '/var/www/rubyapps/smart-recruit'      set :user, 'deploy'  set :pty, false   #There is a known bug that prevents sidekiq from starting when pty is true on Capistrano 3.  set :use_sudo, true  set :deploy_via, :remote_cache    set :linked_files, %w{config/database.yml config/secrets.yml}  set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}      set :branch, 'development'  set :ssh_options, { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub)}  

config/deploy/production.rb

set :stage, :production  server 'myserver.com', roles: %w{web app db}, primary: true  

Capfile

# Load DSL and set up stages  require 'capistrano/setup'    # Include default deployment tasks  require 'capistrano/deploy'  require 'capistrano/bundler'  require 'capistrano/rails'  require 'capistrano/rvm'  require 'capistrano/rails/assets'  require 'capistrano/rails/migrations'  require 'capistrano/faster_assets'  require 'capistrano/passenger'  require 'capistrano/sidekiq'    # Load custom tasks from `lib/capistrano/tasks` if you have any defined  Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }      set :rvm_type, :user  set :rvm_ruby_version, '2.3.1'  

I verified that passenger + apache is working fine on the server.

Note: It works perfectly for Ruby 2.2.2 and Capistrano 3.5.0 in other applications

Rails 5 - model with 2 fields referring to same object

Posted: 03 Oct 2016 06:20 AM PDT

In the app I am building to learn RoR, I have a model "Document" and a model "Business Partner". On the "Document" model, I have 2 fields ("Sender" and "Receiver") referring to the model "Business Partner".

How do I model twice a belongs_to the same target with different fields? What should the migration be?

Related question: how do I model the relationship to it self for business partner? i.e. one company has many business partners, yet can be a business partner too. Note - not to the same record (company A cannot have a relationship to company A (itself).

Rails to Heroku deployment -> Sass::SyntaxError: Invalid CSS after " bootstrap": expected ";", was ".css"

Posted: 03 Oct 2016 04:36 AM PDT

I've been searching for an answer for quite sometime but can't seem to solve, so I'm hopping that I can reach it with some help.

I'm trying to deploy a rails application to Heroku but it gives me the following error:

rake aborted! Sass::SyntaxError: Invalid CSS after " bootstrap": expected ";", was ".css" (sass):6146 /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:1189:in expected' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:1125:inexpected' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:1120:in tok!' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:777:inblock in try_declaration' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:1165:in call' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:1165:inrethrow' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:782:in try_declaration' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:711:indeclaration_or_ruleset' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:676:in block_child' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:668:inblock_contents' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:657:in block' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:649:inruleset' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:675:in block_child' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:668:inblock_contents' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:125:in stylesheet' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/scss/parser.rb:41:inparse' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/engine.rb:406:in _to_tree' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sass-3.4.22/lib/sass/engine.rb:281:inrender' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/sass_compressor.rb:48:in call' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/sass_compressor.rb:28:incall' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:75:in call_processor' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:57:inblock in call_processors' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:56:in reverse_each' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:56:incall_processors' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:134:in load_from_unloaded' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:60:inblock in load' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:317:in fetch_asset_from_dependency_cache' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:44:inload' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/cached_environment.rb:20:in block in initialize' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/cached_environment.rb:47:inyield' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/cached_environment.rb:47:in load' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/base.rb:66:infind_asset' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/base.rb:73:in find_all_linked_assets' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/manifest.rb:142:inblock in find' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:114:in block (2 levels) in logical_paths' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:228:inblock in stat_tree' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:212:in block in stat_directory' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:209:ineach' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:209:in stat_directory' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:227:instat_tree' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:105:in each' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:105:inblock in logical_paths' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:104:in each' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:104:inlogical_paths' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/manifest.rb:140:in find' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/sprockets/manifest.rb:185:incompile' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:68:in block (3 levels) in define' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.0/lib/rake/sprocketstask.rb:147:inwith_logger' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:67:in block (2 levels) in define' /tmp/build_1cc2a72cadb401f09a57ebad6ed802d1/vendor/bundle/ruby/2.2.0/gems/rake-11.3.0/exe/rake:27:in'

Pre compiling locally, even with the RAILS_ENV=production activated, works without any issue, but when I push to Heroku this error comes up.

Thank you in advance!

Link two attributes to one form element

Posted: 03 Oct 2016 04:13 AM PDT

I want to be able to have one select which specifies the value of two model attributes. Therefore if you were to select "yes" on a drop-down it would set the value of attribute a and attribute b to "yes" when the form is submitted. Although the below doesnt work it might help explain what I mean:

= f.select :trial, :free , [['Yes', 'true'], ['No', 'false']], {}, class: 'selectpicker mandatory'  

Rails new object with store_accessor and Postgresql jsonb fails

Posted: 03 Oct 2016 04:04 AM PDT

I have a model Car which has a jsonb field for extra data.

class Car < ApplicationRecord    store_accessor :data, :extra_options  end    class AddDataToCars < ActiveRecord::Migration[5.0]    def change      add_column :cars, :data, :jsonb, null: false, default: '{}'      add_index  :cars, :data, using: :gin    end  end  

I can seed my table with:

car = Car.create!({    make: 'Lada',    model: 'Niva',    data: {      extra_options: 'Some options'    }  })  

and then get and set the extra_options field with:

car.extra_options    # => "Some options"  car.extra_options = "Other options"    # => "Other options"  

However I cannot create a new object and then straight away set the extra_options field

car = Car.new    # => #<Car id: nil, make: nil, model: nil, created_at: nil, updated_at: nil, data: "{}">  car.extra_options = "Some option"    # IndexError: string not matched    # ...  

I can do

car.data = { extra_options: 'options' }    # => {:extra_options=>"options"}  car.extra_options    # => "options"  

But I would like the extra_options field to behave like a normal field so I can easily use it in my views like

<%= form_for(rating) do |f| %>    <%= f.label :extra_options %>    <%= f.text_field :extra_options %>  <% end %>  

Is that at all possible? If not, how do I create a text field in the view that writes to the extra_options field?

force capistrano to use bundle exec on sidekiq start

Posted: 03 Oct 2016 03:54 AM PDT

I use capistrano-sidekiq.

bundle exec cap production sidekiq:start  

results in:

HOME/.rbenv/bin/rbenv exec sidekiq --index 0 --pidfile /home/ubuntu/cap/shared/tmp/pids/sidekiq-0.pid --environment production --logfile /home/ubuntu/cap/shared/log/sidekiq.log --daemon  

How do I make the above command produce the following (note bundle exec):

HOME/.rbenv/bin/rbenv exec bundle exec sidekiq --index 0 --pidfile /home/ubuntu/cap/shared/tmp/pids/sidekiq-0.pid --environment production --logfile /home/ubuntu/cap/shared/log/sidekiq.log --daemon  

Form submit button not showing

Posted: 03 Oct 2016 03:57 AM PDT

I'm working on a project where I'm trying to implement a voting system, but I'm having some trouble, I've tried creating a form with a hidden field:

       <% form_for :vote, url: votes_path do |f| %>            <%= f.hidden_field :rating, value: '1' %></td>            <%= form_submit_button("vote 1") %>         <% end %>  

But when I run that the submit button does not appear, I'm not really sure what I'm doing wrong.

Rails associated models with radio buttons

Posted: 03 Oct 2016 03:46 AM PDT

I have a boat model and I would like to show to user water sports equipment. User can select either available or optional radio button in boat#new action.

But the problem is I could not find how to associate them.

Here how it will look like;

enter image description here

Then for boat#show action I would like to show whether they are available or optional. I do not want to put;

has_one :canoe  has_one :fishing equipment  has_one : wakeboard  ...  

to boat model for every each of the water sport.

How can I do that in an efficient way?

ActionCable delete message

Posted: 03 Oct 2016 03:45 AM PDT

I followed this tutorial to create a chat with ActionCable and Devise: https://www.sitepoint.com/create-a-chat-app-with-rails-5-actioncable-and-devise/

But it's essential, that a message can be deleted too. How can this be done, so that the message is disapearing from all the userscreens simultaniously.

Here are my files: rooms.coffee

jQuery(document).on 'turbolinks:load', ->    messages = $('#messages')    if $('#messages').length > 0      messages_to_bottom = -> messages.scrollTop(messages.prop("scrollHeight"))        messages_to_bottom()        App.global_chat = App.cable.subscriptions.create {        channel: "ChatRoomsChannel"        chat_room_id: messages.data('chat-room-id')      },      connected: ->        # Called when the subscription is ready for use on the server        disconnected: ->        # Called when the subscription has been terminated by the server        received: (data) ->        messages.append data['message']        messages_to_bottom()        send_message: (message, chat_room_id) ->        @perform 'send_message', message: message, chat_room_id: chat_room_id        $('#new_message').submit (e) ->      $this = $(this)      textarea = $this.find('#message_body')      if $.trim(textarea.val()).length > 1        App.global_chat.send_message textarea.val(), messages.data('chat-room-id')        textarea.val('')      e.preventDefault()      return false  

message_broadcast_job.rb

class MessageBroadcastJob < ApplicationJob    queue_as :default      def perform(message)      ActionCable.server.broadcast "chat_rooms_#{message.guild.id}_channel",                               message: render_message(message)    end      private      def render_message(message)      MessagesController.render partial: 'messages/message', locals: {message: message}   end  end  

chat_rooms_channel.rb

class ChatRoomsChannel < ApplicationCable::Channel    def subscribed      stream_from "chat_rooms_#{params['chat_room_id']}_channel"    end      def unsubscribed      # Any cleanup needed when channel is unsubscribed    end      def send_message(data)      current_user.messages.create!(body: data['message'], guild_id: data['chat_room_id'])    end  end  

message.rb

class Message < ApplicationRecord    belongs_to :user    belongs_to :guild    validates :body, presence: true, length: {minimum: 2, maximum: 1000}      def timestamp      created_at.strftime('%H:%M:%S %d %B %Y')    end    after_create_commit { MessageBroadcastJob.perform_later(self) }   end  

I want to have a destroy_link on every message.

Rails 5 - implement reusable comment model - views?

Posted: 03 Oct 2016 03:01 AM PDT

In my app that I am building to learn RoR, I have a similar situation like this question. Now my question is how to change my views for this?

I have an Annotation model, a Document model and a Comment model. If I switch to a polymorphic association such that my Annotations and my Documents can have Comments, how to do the view (in the partial)?

This is the current partial:

<%= simple_form_for([@annotation, @annotation.comments.build], html: { class: 'form-vertical', multipart: true }) do |f| %>       <%= f.error_notification %>       <%= f.input :commenter, :as => :hidden, :input_html => { :value => current_user.username }, label: false %>       <%= f.input :body, placeholder: 'comment', focus: true, label: false %>       <%= f.button :submit, 'Save' %>    <% end -%>  

Create a model record when a button is pressed

Posted: 03 Oct 2016 03:18 AM PDT

I'm working on a project, and I'm trying to implement a feedback system. There are three buttons, positive, neutral and negative and at the moment when the user clicks a button they are asked if they want to submit more feedback and are taken to the new feedback form. However instead what I want is that when a button is pressed a record is saved with the rating field of the model set by which button they pressed.

Then when a user gives more feedback they are taken to the edit page for that feedback. I'm not really sure how to go about doing this, would I need some javascript on the buttons? or does rails have a method that will do this?

Thank you