Wednesday, March 23, 2016

uninitialized constant DocumentsController::PDFKit | Fixed issues

uninitialized constant DocumentsController::PDFKit | Fixed issues


uninitialized constant DocumentsController::PDFKit

Posted: 23 Mar 2016 07:14 AM PDT

I have been trying for a couple of hours to get PDFKit working with my app.

I am getting an error of Mime::Type.register "application/pdf", :pdf when I try to generate a pdf.

The pdfkit gem is installed wkhtmltopdf is installed and seems to be running ok

mime_types.rb  Mime::Type.register "application/pdf", :pdf  

.

pdfkit.rb  PDFKit.configure do |config|    config.wkhtmltopdf = 'C:\wkhtmltopdf\bin\wkhtmltopdf.exe'  end  

My Show def in the documents Controller includes

pdf = PDFKit.new('test')  send_data(pdf.to_pdf)    respond_to do |format|    format.html # show.html.erb    format.json { render json: @document }    format.csv { send_data @documents.as_csv }  

Note that there is no format.pdf

application.rb has

require 'pdfkit'  config.middleware.use PDFKit::Middleware  

If I go to my documents index it shows OK. If I add .pdf, I get

ActionController::UnknownFormat in DocumentsController#index  ActionController::UnknownFormat    Rails.root: C:/inetpub/wwwroot/development/research_library_new    Application Trace | Framework Trace | Full Trace  app/controllers/documents_controller.rb:40:in `index'  

It appears that it is looking for format.pdf in the respond_to block

If I try to show one of the documents, I get

NameError in DocumentsController#show  uninitialized constant DocumentsController::PDFKit    Rails.root: C:/inetpub/wwwroot/development/research_library_new    Application Trace | Framework Trace | Full Trace  app/controllers/documents_controller.rb:84:in `show'  Request    Parameters:    {"id"=>"10"}  

I checked with a rake middleware and pdfkit is installed as middleware.

Rails ajax, not able to append new record in table

Posted: 23 Mar 2016 07:02 AM PDT

I am trying to use ajax in my rails application. My ajax is working fine while displaying _form to create new student record. But once I create new student I want to hide the _form and display list of students with new student record added at bottom of table.

Currently my code is creating new student record, hiding the new _form and showing the list of students. But due to some reason the new student record is not getting appended at the bottom of the table. Once I refresh the page then I can see the record of new student displayed at the bottom on the table. But I would like to achieve this behaviour without refreshing the page.

Below are my codes:

students_controller.rb

  def index      @students = Student.all    end      def new      @student = Student.new    end      def create      @student = Student.new(student_params)      @student.save    end      private       def student_params      params.require(:student).permit(:name)    end  

index.html.erb file

<div id="student-list">    <h1>Listing Students</h1>      <table>      <thead>        <tr>          <th>Name</th>          <th colspan="3"></th>        </tr>      </thead>        <tbody>        <div id='all-students'>          <%= render @students %>        </div>      </tbody>    </table>      <br>      <%= link_to 'New Student', new_student_path, remote: true %>    </div>    <div id='new-form'></div>  

_student.html.erb partial

<tr>    <td><%= student.name %></td>    <td><%= link_to 'Show', student %></td>    <td><%= link_to 'Edit', edit_student_path(student) %></td>    <td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Ary you sure?' } %></td>  </tr>  

new.js.erb file (this one is working fine)

$("#student-list").hide();  $("#new-form").html("<%= j render 'form' %>");  

_form.html.erb partial

<%= form_for(@student, remote: true) do |f| %>    <div class="field">      <%= f.label :name %><br>      <%= f.text_field :name %>    </div>    <div class="actions">      <%= f.submit %>    </div>  <% end %>    <%= link_to '<< back', students_path, remote: true %>  

create.js.erb file (this is the file which is not working)

$("#all_students").append("<%= j render @student %>");  $("#new-form").hide();  $("#student-list").show();  

I am using Rails 4.2.5 and ruby 2.3.0

Here is output from rails server

Started POST "/students" for ::1 at 2016-03-24 00:44:23 +1100  Processing by StudentsController#create as JS    Parameters: {"utf8"=>"✓", "student"=>{"name"=>"dd"}, "commit"=>"Create Student"}     (0.1ms)  begin transaction    SQL (0.3ms)  INSERT INTO "students" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "dd"], ["created_at", "2016-03-23 13:44:23.465302"], ["updated_at", "2016-03-23 13:44:23.465302"]]     (0.7ms)  commit transaction    Rendered students/_student.html.erb (0.4ms)    Rendered students/create.js.erb (8.4ms)  Completed 200 OK in 21ms (Views: 18.6ms | ActiveRecord: 1.0ms)  

Here is output from browser (Chrome -> Network -> XHR)

$("#all_students").append("<tr>\n  <td>dd<\/td>\n  <td><a href=\"/students/43\">Show<\/a><\/td>\n  <td><a href=\"/students/43/edit\">Edit<\/a><\/td>\n  <td><a data-confirm=\"Ary you sure?\" rel=\"nofollow\" data-method=\"delete\" href=\"/students/43\">Destroy<\/a><\/td>\n<\/tr>\n");  $("#new-form").hide();  $("#student-list").show();  

Javascript not always loaded, but it's included in head

Posted: 23 Mar 2016 07:00 AM PDT

I have Ruby on Rails project, where I use a third party library (editablegrid). I placed the files in vendor/assets/javascripts and I have included the library in the layout file that for views that need it:

<!DOCTYPE html>  <html>  <head>    <title>Mcf</title>    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'dynamic_collections' %>    <%= csrf_meta_tags %>    <%= javascript_include_tag "editablegrid" %>    <%= javascript_include_tag "editablegrid_editors" %>    <%= javascript_include_tag "editablegrid_renderers" %>    <%= javascript_include_tag "editablegrid_utils" %>    <%= javascript_include_tag "editablegrid_validators" %>  </head>    <body>      <%= yield %>    </body>  

The generated html always has the <script> tags for editablegrid, but the browser does not always load it. The js files can always be loaded from the urls generated by javascript_include_tag.

The pattern I noticed in whether js loads or not is that, js won't load if I click a link leading to the page except if js already loaded once on the same tab. Typing the page's url in the addressbar or refeshing the page will load js. I tested this pattern on Chromium.

In Chromium's Elements devtool only editablegrid javascripts don't show up, all other js files seem to be loaded.

Versions:

Ruby 2.2.3p173 (2015-08-18 revision 51636)  Rails 4.2.5  Chromium 47.0.2526.106 Ubuntu 14.04 (64-bit)  Firefox 43.0.4 (Bug is there, didn't test for pattern)  

Stripe OAuth - redirect URL = "Heroku | No such app"

Posted: 23 Mar 2016 07:01 AM PDT

Having some trouble with my redirect URL for Stripe Connect when hosted on Heroku.

Running locally, it all works as expected, users connect with OAuth, with their publishable key save to the database, and then proceeding as normal through the site.

On Heroku however, users connect to Stripe via OAuth, entering their details and password, then on redirect, they are greeted with the following error message:

Heroku | No such app  There is no app configured at that hostname.  Perhaps the app owner has renamed it, or you mistyped the URL.  

The documentation has not helped so far, and I haven't been able to find anything similar on Stack Overflow.

Stripe Details:

Production Redirect URI: https://www.hidden-hamlet-51741.herokuapp.com/oauth/callback

I have played around with some variations, however have had no success.

Heroku Logs:

2016-03-23T13:23:37.799909+00:00 heroku[router]: at=info method=GET path="/users/auth/stripe_connect" host=hidden-hamlet-51741.herokuapp.com request_id=4d52e646-6d02-45be-87e6-7492665c4d17 fwd="86.138.166.211" dyno=web.1 connect=2ms service=19ms status=302 bytes=1549      2016-03-23T13:23:37.796546+00:00 app[web.1]: Started GET "/users/auth/stripe_connect" for 86.138.166.211 at 2016-03-23 13:23:37 +0000      2016-03-23T13:23:37.799240+00:00 app[web.1]: I, [2016-03-23T13:23:37.799170 #3]  INFO -- omniauth: (stripe_connect) Request phase initiated.      2016-03-23T13:30:57.289321+00:00 app[web.1]: Started GET "/users/auth/stripe_connect" for 86.138.166.211 at 2016-03-23 13:30:57 +0000      2016-03-23T13:30:57.306551+00:00 app[web.1]: I, [2016-03-23T13:30:57.306458 #3]  INFO -- omniauth: (stripe_connect) Request phase initiated.      2016-03-23T13:30:57.309718+00:00 heroku[router]: at=info method=GET path="/users/auth/stripe_connect" host=hidden-hamlet-51741.herokuapp.com request_id=e7805fd0-3973-4a27-b842-433e1dbb1532 fwd="86.138.166.211" dyno=web.1 connect=2ms service=30ms status=302 bytes=1549  

Any pointers would be super helpful.

Thanks.

How to create button with rails that add input fields with javascript

Posted: 23 Mar 2016 06:36 AM PDT

What is the best practice to create a button with a rails form_helper that will generate through Javascript/JQuery new input fields ?

(This button is supposed to be used within a form with nested objects)

N.B. : My app is actually running with rails 3.2, but I want it to be compatible with rails 4 and 5.

Wrong number of arguments (1 for 2) for update method

Posted: 23 Mar 2016 06:35 AM PDT

I'm having an issue tracking down why my update method isn't getting the needed arguments. I have a similar test for show and the payloads are working. In this scenario the route in question is invoice/invoice_id/trip/id. If you can help me spot the error and give any suggestions on how to troubleshoot this type of problem in the future that'd be great.

This is the update method.

def update    if @trip.update(@trip.trip_id, trip_params)      head :no_content    else      render json: [@invoice, @trip].errors, status: :unprocessable_entity    end  end  

With the following private methods.

private      def set_trip      @trip = Trip.where(:invoice_id => params[:invoice_id], :trip_id => params[:id] )    end      def trip_params      params.require(:trip).permit(:trip_id, :depart_airport, :arrive_airport, :passenger_first_name, :passenger_last_name, :passenger_count, :departure_date, :merchant_id)    end      def load_invoice      @invoice = Invoice.find(params[:invoice_id])    end    end  

My failing test looks like this.

test "should update trip" do    put :update, invoice_id: @invoice.invoice_id, id: @trip,     trip: {arrive_airport: @trip.arrive_airport,     depart_airport: @trip.depart_airport,     departure_date: @trip.departure_date,     passenger_count: @trip.passenger_count,     passenger_first_name: @trip.passenger_first_name,      passenger_last_name: @trip.passenger_last_name}   assert_response 204  end  

Only allow user to create one feedback for each movies

Posted: 23 Mar 2016 06:49 AM PDT

I have three models, User, Movie, and Review. Here is the relation:

# User.rb  has_many :movies  has_many :reviews    # Movie.rb  belongs_to :user  has_many :reviews    # Review.rb  belongs_to :movies  belongs_to :users  

Here is the routes:

# routes.rb  resources :movies do   resources :reviews  end  

Here is the controller:

# reviews_controller.rb  class ReviewsController < ApplicationController    before_action authenticate_user!    before_action :find_movie    before_action :find_review, only: [:edit, :update, :destroy]      def new      @review = Review.new    end      def create      @review = Review.new(review_params)        if @review.save        redirect_to movie_path(@movie)      else        render 'new'      end    end      def edit    end      def update      if @review.update(review_params)        redirect_to movie_path(@movie)      end    end      private      def find_movie        @movie = Movie.find(params[:movie_id])      end        def find_review        @review = Review.find(params[:id])      end        def review_params        params.require(:review).permit(:rating, :comment)      end  end  

I created a new and partial form and then in the show page of the movie, I create this line of code to show the button of creating new review for a particular movie:

# views/movies/show.html.erb  <%= link_to 'Give review', new_movie_review_path(@movie) %>  

I don't want the user to create another review after they submit a review for the same movie. That's why I want to hide the "Give review" button if the user is already gave the feedback. How do I do that?

Ruby on rails api unable to delete

Posted: 23 Mar 2016 06:37 AM PDT

I have used scaffold to generate simple application, I'm able to perform GET and POST via chrome extension tool called "PostMan", However I'm unable to perform DELETE action via this tool, I'm getting:

No route matches [DELETE] "/settings.json/18"  

I have checked routes.rb

Rails.application.routes.draw do    resources :settings  

And deleting record via default scaffold works, only when I'm performing an API call.

Console log displays the following:

 ActionController::RoutingError (No route matches [DELETE] "/settings.json/18"):    actionpack (4.2.5) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'    web-console (2.3.0) lib/web_console/middleware.rb:20:in `block in call'    web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'  

I'm not sure what else to check, any input is hightly appreicate it.

Playing sound on Rails server on request of Client

Posted: 23 Mar 2016 06:37 AM PDT

I want to play music files on server machine which is connected to a stereo system but on the request of a client side.

The client opens the web app through the URL and click play and the sound play on the server machine. (I don't want to stream)

At the moment my sound file is located in the same directory as the Controller but when I press the play button from a browser nothing happen.

This might be very straightforward but as a Beginner I am finding it difficult to execute system command on the host.

So far I have this client interface on localhost:3000 enter image description here

I have a controller defined which handles the request from play button.

class WelcomeController < ApplicationController def index
end

def play    `mplayer myfile.mp3`    head :ok  end  

end

Routes.rb

Rails.application.routes.draw do    root 'welcome#index'    get "/play" => "welcome#play"  end  

Output of Rake Routes

Prefix Verb URI Pattern     Controller#Action  root GET  /               welcome#index  play GET  /play(.:format) welcome#play  

Index.html.erb

<h1>Play it!</h1>  <%= link_to "Play", play_path, remote: true %>  

Query Range field type in Mongoid

Posted: 23 Mar 2016 06:16 AM PDT

Using Rails 4.2 & Mongoid 5.1

I have a field with type range. I need to query for a document that has a given number in the range.

Class User   has_many :age_rules   field :age, type: Integer  end        Class AgeRule    belongs_to :user    field :age_range, type: Range    field :score, type: Integer  end  

AgeRule has one record:

*#<AgeRule _id: 56700e, age_range: {"min"=>10, "max"=>100}, score: 1.0>*  

I need to retrieve the record based on the age of the user. I tried

AgeRule.find_by(age_range: 10)  

Serving Rails' precompiled assets using nginx in Docker

Posted: 23 Mar 2016 06:08 AM PDT

Currently I'm setting up my app using docker. I've got a minimal rails app, with 1 controller. You can get my setup by running these:

rails new app --database=sqlite --skip-bundle  cd app  rails generate controller --skip-routes Home index  echo "Rails.application.routes.draw { root 'home#index' }" > config/routes.rb  echo "gem 'foreman'" >> Gemfile  echo "web: rails server -b 0.0.0.0" > Procfile  echo "port: 3000" > .foreman  

And I have the following setup:

Dockerfile:

FROM ruby:2.3    # Install dependencies  RUN apt-get update && apt-get install -y \        nodejs \        sqlite3 \        --no-install-recommends \        && rm -rf /var/lib/apt/lists/*    # Configure bundle  RUN bundle config --global frozen 1  RUN bundle config --global jobs 7    # Expose ports and set entrypoint and command  EXPOSE 3000  CMD ["foreman", "start"]    # Install Gemfile in different folder to allow caching  WORKDIR /tmp  COPY ["Gemfile", "Gemfile.lock", "/tmp/"]  RUN bundle install --deployment    # Set environment  ENV RAILS_ENV production  ENV RACK_ENV production    # Add files  ENV APP_DIR /app  RUN mkdir -p $APP_DIR  COPY . $APP_DIR  WORKDIR $APP_DIR    # Compile assets  RUN rails assets:precompile  VOLUME "$APP_DIR/public"  

Where VOLUME "$APP_DIR/public" is creating a volume that's shared with the Nginx container, which has this in the Dockerfile:

FROM nginx    ADD nginx.conf /etc/nginx/nginx.conf  

And then docker-compose.yml:

version: '2'    services:    web:      build: config/docker/web      volumes_from:        - app      links:        - app:app      ports:        - 80:80        - 443:443    app:      build: .      environment:        SECRET_KEY_BASE: 'af3...ef0'      ports:        - 3000:3000  

This works, but only the first time I build it. If I change any assets, and build the images again, they're not updated. Possibly because volumes are not updated on image build, I think because how Docker handles caching.

I want the assets to be updated every time I run docker-compose built && docker-compose up. Any idea how to accomplish this?

Angular in Rails requires precompile

Posted: 23 Mar 2016 06:05 AM PDT

I am new to Angular so my config needs help. When I edit an Angular file I must precompile assets to see changes on development.

rake assets:precompile  

Normally, I only precompile for production before pushing to Heroku. What can I do to avoid this step?

I have simple setup using bower-rails gem.

application.js

//= require angular  

Gemfile

gem 'bower-rails'  

vendor/Bowerfile

asset 'angular', '~1.5'  resolution 'angular', '1.5'  

app/assets/javascripts/some-file.js

(function(){     console.log("outside angular stuff shows on page load");    angular.module('ads',[])    .controller("AdSearchController", [      "$scope", "$http",      function($scope, $http) {            console.log("inside angular stuff does not show unless precompiled");      ...  

The view calling the angular controller is located in: app/views/thing/daview.html.erb

Incidentally, I am also getting this console warning which may be related:

outside angular stuff shows on page load  application-e058e14….js?body=1:51201 WARNING: Tried to load angular more than once.  

No route matches [POST] "/users/1/contacts/new"

Posted: 23 Mar 2016 06:01 AM PDT

app/views/contacts/new.html.erb

<h2>Add New Contact</h2>        <div class="row">        <div class="col-md-8">        <%= simple_form_for @contact, :url => new_user_contact_path do |f| %>          <div class="form-group">            <%= f.label :first_name %>            <%= f.text_field :first_name, class: "form-control" %>          </div>          <div class="form-group">            <%= f.label :last_name %>            <%= f.text_field :last_name, class: "form-control" %>          </div>          <div class="form-group">            <%= f.input :date_of_birth, as: :date,  discard_year:true, order:[:day, :month] %>          </div>          <div class="form-group">            <%= f.label :sex %>            <%= f.select :sex, [:male, :female], class: "form-control" %>          </div>          <div class="form-group">            <%= f.label :phone_number %>            <%= f.text_field :phone_number, class: "form-control" %>          </div>          <div class="form-group">            <%= f.label :address %>            <%= f.text_area :address, class: "form-control" %>          </div>          <div class="form-group">            <%= f.button :submit, "Submit", class: "btn btn-success btn-md btn-block" %>            </div>          </div>        <% end %>        </div>      </div>        <%= link_to "Back", user_contacts_path %>  

My routes when I run rake routes

 Prefix Verb   URI Pattern                                 Controller#Action              new_user_session GET    /users/sign_in(.:format)                    devise/sessions#new                  user_session POST   /users/sign_in(.:format)                    devise/sessions#create          destroy_user_session DELETE /users/sign_out(.:format)                   devise/sessions#destroy                 user_password POST   /users/password(.:format)                   devise/passwords#create             new_user_password GET    /users/password/new(.:format)               devise/passwords#new            edit_user_password GET    /users/password/edit(.:format)              devise/passwords#edit                               PATCH  /users/password(.:format)                   devise/passwords#update                               PUT    /users/password(.:format)                   devise/passwords#update      cancel_user_registration GET    /users/cancel(.:format)                     devise/registrations#cancel             user_registration POST   /users(.:format)                            devise/registrations#create         new_user_registration GET    /users/sign_up(.:format)                    devise/registrations#new        edit_user_registration GET    /users/edit(.:format)                       devise/registrations#edit                               PATCH  /users(.:format)                            devise/registrations#update                               PUT    /users(.:format)                            devise/registrations#update                               DELETE /users(.:format)                            devise/registrations#destroy                 user_contacts GET    /users/:user_id/contacts(.:format)          contacts#index                               POST   /users/:user_id/contacts(.:format)          contacts#create              new_user_contact GET    /users/:user_id/contacts/new(.:format)      contacts#new             edit_user_contact GET    /users/:user_id/contacts/:id/edit(.:format) contacts#edit                  user_contact GET    /users/:user_id/contacts/:id(.:format)      contacts#show                               PATCH  /users/:user_id/contacts/:id(.:format)      contacts#update                               PUT    /users/:user_id/contacts/:id(.:format)      contacts#update                               DELETE /users/:user_id/contacts/:id(.:format)      contacts#destroy                         users GET    /users(.:format)                            users#index                               POST   /users(.:format)                            users#create                      new_user GET    /users/new(.:format)                        users#new                     edit_user GET    /users/:id/edit(.:format)                   users#edit                          user GET    /users/:id(.:format)                        users#show                               PATCH  /users/:id(.:format)                        users#update                               PUT    /users/:id(.:format)                        users#update                               DELETE /users/:id(.:format)                        users#destroy                         index GET    /index(.:format)                            redirect(301, /)                          root GET    /                                           high_voltage/pages#show {:id=>"index"}                          page GET    /pages/*id                                  high_voltage/pages#show  

config/routes.rb

Rails.application.routes.draw do        devise_for :users          resources :users do          resources :contacts        end      end  

My new and create action in ContactsController

     def new          @contact = Contact.new        end          def create          @contact = Contact.new(contact_params)          @contact.user = current_user          if @contact.save            flash[:success] = "Contact was successfully created!"            redirect_to @contact.user          else            render :new          end        end  

This is the issue: I get the error: No route matches [POST] "/users/1/contacts/new" when I submit the form at http://localhost:3000/users/1/contacts/new. What could be the issue?

Rails group by hour of the day for created_at column

Posted: 23 Mar 2016 06:59 AM PDT

I have a Subscribe Model and want to group by hour of day. I checked with rails group records by dates of created_at and rails - group by day as well as hour But no luck!.

2.3.0 :175 > Subscribe.find 13    Subscribe Load (0.9ms)  SELECT  "subscribes".* FROM "subscribes" WHERE "subscribes"."id" = $1 LIMIT 1  [["id", 13]]   => #<Subscribe id: 13, user_id: 7, publisher_id: 5, created_at: "2015-11-23 00:37:49", updated_at: "2016-03-22 08:04:31", subscription_id: "2">   

on applying the other solution

2.3.0 :174 > Subscribe.where("DATE_PART('hour', created_at) = ?", 13)    Subscribe Load (1.0ms)  SELECT "subscribes".* FROM "subscribes" WHERE (DATE_PART('hour', created_at) = 13)   => #<ActiveRecord::Relation []>   

To achieve this I used groupdate

graph_data =  Subscribe.group_by_hour_of_day(:created_at, format: "%-l %M %P", time_zone: "Kolkata",range: start_date.to_datetime..end_date.to_datetime).count     => {"12 00 am"=>0, "1 00 am"=>0, "2 00 am"=>0, "3 00 am"=>0, "4 00 am"=>0, "5 00 am"=>1, "6 00 am"=>1, "7 00 am"=>0, "8 00 am"=>0, "9 00 am"=>0, "10 00 am"=>0, "11 00 am"=>0, "12 00 pm"=>1, "1 00 pm"=>1, "2 00 pm"=>0, "3 00 pm"=>0, "4 00 pm"=>0, "5 00 pm"=>0, "6 00 pm"=>0, "7 00 pm"=>0, "8 00 pm"=>0, "9 00 pm"=>0, "10 00 pm"=>0, "11 00 pm"=>0}   

but for Subscribe 13 there is an record at created_at (2015-11-23 00:37:49) but it return as 0

Any help would be appreciated!!!

how can I post the data from controller to a web service in json format in rails [on hold]

Posted: 23 Mar 2016 05:49 AM PDT

I want to post data in json format to a web service in rails, please give me sample rails code with explanation and proper syntax.

How to compare a Hask Key with an Integer in rails

Posted: 23 Mar 2016 05:51 AM PDT

   params[:mg_question_id].each do |question|           @poll=MgPollData.new           @poll.mg_question_id= question           params[:options_id].each do |k,v|              if k==question              @poll.answer= v            end           end           @poll_answers.save       end   

here, im comparing the array value with the hash key. But hash key is string and array is integer. thats why im unable to compare the both.

Is there any solution regarding this ?

Do number of API calls in the background with delay

Posted: 23 Mar 2016 05:33 AM PDT

Can you help me to choose strategy. I want to do number of API calls in the background with delay. I prefer to use ActiveJob with Sidekiq.

For example, my worker should do 1000 API calls, but should be delay 60 seconds among them. Sure, I just can use sleep(60), it's good for performance(a thread should sleep), but performing of a worker will take 17 hours.

Does it mean if I have 100 such tasks like this one, I should start 100 workers to perform them asynchronously? Or you can suggest other way to improve that, because this queue can be handled by 10 workers and I need some workers for other stuff(email notification, updates etc).

Is it good to start sidekiq with 300 workers in a process?

Rails API for fb login with Ionic

Posted: 23 Mar 2016 05:33 AM PDT

I want to build a rails api for fb login using, ionic framework. Till now I've successfully created a web base application and it's successfully authenticating with Facebook.

Now I want to do the same but with ionic based app.

Questions?

  1. Is this possible to write a rails api using omniauth and using the fb authentication api with ionic.
  2. If it's(1) is possible than what kind of json request is to be made or returned.

Couldn't find anything over the web about it, nor any github project of rails with ionic (fb login).

My Current code:

Controller:

  class SessionsController < ApplicationController    def create      user = User.from_omniauth(env["omniauth.auth"])      session[:user_id] = user.id      redirect_to root_url        end      def destroy      session[:user_id] = nil      redirect_to root_url    end  end  

Model:

class User < ActiveRecord::Base    def self.from_omniauth(auth)      where(provider: auth.provider, uid: auth.uid).first_or_initialize do |user|        user.provider = auth.provider        user.uid = auth.uid        user.name = auth.info.name        user.oauth_token = auth.credentials.token        user.oauth_expires_at = Time.at(auth.credentials.expires_at)        user.save!      end    end  end  

Initializers:

OmniAuth.config.logger = Rails.logger  Rails.application.config.middleware.use OmniAuth::Builder do    provider :facebook, "123", "abc"  end  

Rendering JS.ERB results in raw code

Posted: 23 Mar 2016 05:48 AM PDT

When an AJAX request executes, show.js.erb renders the partial _article.haml.

What I want to be able to do in show.js.erb is to write:

<%= j render  'article' %>  

Since it has a .js extension I am required to wrap this in JavaScript (the example above does not render the partial), so:

'<%= j render  'article' %>' OR ('<%= j render  'article' %>');  

This would render the partial but with raw code--including HTML and JS escaping.

('things will go back to \"normal.\"<\/p>\n\n');  

What's the right way to do this?

welcome#index:

.ajax_load.article-content{ data: { 'remote-url' => article_path(@article) } }  

articles.js:

 $(document).ready(function() {    $('.ajax_load').each(function(index, element) {      var url = $(element).data('remote-url')      if (url) {        $.get(url, function(responseText) {          $(element).html(responseText);        })      } else {        console.log("missing url for ajax!")      }    })  })  

RSpec: how do I correctly simulate #destroy failure

Posted: 23 Mar 2016 06:35 AM PDT

I'm having a very hard time simulating the failure of a destroy method in my controller.

My controller's destroy looks like this:

def destroy     project = Project.find(params[:id])     project.destroy      if project.destroyed?      render json: {        project: nil,        message: "The project was successfully deleted"      }    else      render json: {        message: "Could not delete project",      }, status: :unprocessable_entity    end  end  

I'm trying to render the json in the else block in my test, but can't get it done. So far the particular test looks like this:

describe "DELETE #destroy" do     let!(:project) { create(:project, :open) }      context "when invalid" do       it "returns an error if the project was not deleted" do       expect(Project).to receive(:find).with(project.id.to_s).and_call_original       expect(project).to receive(:destroy).and_return(false)       delete :destroy, id: project     end     end  end  

The test either returns the 'happy path' or gives me errors. At the moment:

 Failure/Error: expect(project).to receive(:destroy).and_return(false)           (#<Project:0x007f87cf5d46a8>).destroy(*(any args))             expected: 1 time with any arguments             received: 0 times with any arguments  

If anyone could point me in the right direction, and explain how I can simulate a 422, I'd be very grateful!

Save CarrierWave Upload as Base64

Posted: 23 Mar 2016 05:12 AM PDT

I would like to take an uploaded attachment from CarrierWave and save it as a Base64 string in my database table, as opposed to saving the path of the upload.

I have absolutely no idea where to start the process. I tried to create the following:

........    before_create :process_image      mount_uploader :image_upload, ImageUploader    .......    attr_accessible :name, :image_upload, :authentication_type    attr_reader :image    private    def process_image      if !self.image_upload.path.nil?        self.image = Base64.encode64(file.open(self.image_upload.path).read)        self.image_upload = nil      end    end  

However, during the upload I get the following error:

NoMethodError (undefined method `image_upload_will_change!'

I am sure it's something trivial, however, it seems like I am the only one that wants to try this.

Rails using paperclip on google cloud

Posted: 23 Mar 2016 05:10 AM PDT

I have a issue when I upload Images on google cloud using rails and paperclip. Localhost works perfect the issue occurs on production mode.

has_mongoid_attached_file  :image,      :styles => { :large => "380x380!" , :medium => "240x240", :small => "120x120!" },      :storage => :fog,      :fog_public => true,      :fog_directory => 'XXXX',      :path => "images/:id/:style/:basename.:extension",      :fog_credentials => {  :provider => 'Google',                             :google_storage_access_key_id => 'XXXXX',                             :google_storage_secret_access_key => 'XXXXX'}      validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]  

The server returns

has contents that are not what they are reported to be

Thank you for your efforts !! :)

A new form to update a record in Rails 4

Posted: 23 Mar 2016 05:45 AM PDT

I have a Rails 4 app. In this app, I have multiple HABTM relationships between various models. For example, a task can have many learning objectives as well as many missions associated with it. Right now, I have the edit form in modal dialog that edits the task record and is invoked via the edit_task_path(@task) that updates the record. I would like to create a new form that also does that update action; however, I only want this form to be for updating the associations for the tasks. My main question is: how do I create and call a second form to route to the update action for the same record? I would basically like a update_task_path(@task) that handles the update controller action as well. I've looked at various stack overflows and none specifically address a new form for the update controller action.

Rails 4 dynamic includes

Posted: 23 Mar 2016 05:19 AM PDT

I have 3 models

class Song    has_and_belongs_to_many :albums    has_many :posts, as: :songable  end    class UnknownSong    has_many :posts, as: :songable  end    class Posts    belongs_to :songable, polymorphic: true  end  

And I try loading all posts with media inside

post_with_media = Posts.includes(:songable)  post_with_media.each { ... } here N+1 album for song    post_with_media = Posts.includes(songable: :albums) # here raise error because no albums on UnknownSong  

What are best practices to deal with "conditional includes?" and load all posts with songs => albums, unknown_songs?

Rails4 test driven development [on hold]

Posted: 23 Mar 2016 04:26 AM PDT

How is test driven development on rails helpful? Is it okay to test an app using manual test cases on my browser or is it important to use gems like rspec and others to test my app.

Add multiple filters in Spree Commerce Rails

Posted: 23 Mar 2016 04:15 AM PDT

We need to implement custom filters for categories in spree ecommerce in latest version as seen here https://github.com/spree/spree .

We need to do it in a dynamic way because we have about 100 filters or more to make. The ideal solution would be to show all available filters in admin area and admin can activate/deactivate them for each category.

Current Scenario: We know how to make a new filter and apply it. But it takes about four methods per filter as shown in the product_filter.rb file linked below.

Some links we have found useful:

https://gist.github.com/maxivak/cc73b88699c9c6b45a95 https://github.com/radar/spree-core/blob/master/lib/spree/product_filters.rb

Rails Postgres migration without downtime

Posted: 23 Mar 2016 06:23 AM PDT

Let's say I want to add a column on my users table running the following migration

class AddVersionHistoryToUsers < ActiveRecord::Migration    def change      add_column :users, :versions, :string, array: true, default: '{}'      User.find_each do |user|        if user.app_version?          user.versions << user.app_version.to_s          user.save!        end      end    end  end  

My aim is to insert the current app_version of each user into the versions array. How can I execute a migration without a lock in the users table due to the default value?

Rails caches_action and meta tags

Posted: 23 Mar 2016 04:02 AM PDT

I am stuck at what I think is a very simple/common usecase. I want to use "caches_action, layout:false" and display, from the layout, dynamic tags that will be set by the action (either from the view or the controller).

I could not find any standard rails way to do this as content_for does not work with caches_action, instance variables are not cached (?), and all the metatags helper gems (metamagic and meta-tags) do not support (or even mention) this usecase.

Which brings my question:

  • Is there any way to do this ?

Example

I am using caches_action, layout:false on a SandboxController#show method

#app/controllers/sandbox_controller.rb  class SandboxController < ApplicationController      caches_action :show, layout: false, expires_in: 1.minute      def show      @meta_title = "Best page ever"    end    end  

The view

#app/views/sandbox/show.html.erb  We are in show action.  

The layout

#app/views/layouts/application.html.erb  <title><%= @meta_title %></title>  Debug: <%= @meta_title %> <br/>  <%= yield %>  

Thanks !

Can we use Postgres for testing and Mongo for development environment in rails

Posted: 23 Mar 2016 04:17 AM PDT

I have a rails application running with MongoDB for the development environment. We're planning to migrate to an SQL Database (PostgreSQL) and in the process we're first adding RSpec using PostgreSQL as our test database.

I do understand following points:

  • We've ActiveRecord ORM for connecting rails with an SQL Based DB and Mongoid for MongoDB.
  • We've migrations for our test env and no such migrations for dev environment.
  • Our models will turn into this:

    class MyModel < ActiveRecord::Base include Mongoid::Document end

Will there be any blockers if I go with such approach and start adding rspec using PostgreSQL database ?

Rails - Modular many-to-many relations

Posted: 23 Mar 2016 05:57 AM PDT

Context

In the context of a Ruby on Rails application, in a school's project.

Let's consider the context of a team-based game, with many characters to choose from. I want to represent affinities between two characters in different context, which means whether two characters are being teamed-up or are facing each other or even when one is present in the game while the other is missing.

I would then have tables that looks something like this in my database

  • Characters
  • Ally-Relation
  • Enemy-Relation
  • PlayingSingle-Relation

Each of these <name>-Relation tables represents a many-to-many relation between Characters, with an additional score that represents the strongness of the relation

Of course, relations between character are subject to changes. We might decide for any reason that a relation has become irrelevant, or another relation that we didn't thought of before just appeared.

In terms of display, we want to look for both the best and worst other characters in a specific relation.

Question

I came up with something like this.

class Relation < ActiveRecord::Base        scope :best, ->(character_id) {      Character.find(where(character_left: character_id).order("score desc").limit(5).pluck(:character_right))    }  end  

Where character_left and character_right are the two characters to be considered for in the relation and the score is the strenght of the bond.

However, when fetching data, my teacher thinks it would be best to have scopes in the Characters model to find both the best and worst other character in a specific relation. This, because the teammate that is doing, say, the HTML code don't give a damn about the structure of the Relations when he wants to display characters. He told me about using has_and_belongs_to_many and he sketched me some code he would expects that looks something like Character.best(:relation) to fetch the data.

While I think what I did is better (obviously :) ). Having the scopes that will fetch Characters from within the Relation models, as they subject to appear and disappear keeps the request relation specifics. This prevents us from modifying the Characters model every time we fumble with the Relations. Having somethings that looks like Relation.best(:hero) seems cleaner to me.

What do you think about it ? What are good practices around this very specific situation. Are there any right way to apply and use modular many-to-many relation s in a Ruby on Rails application ?

1 comment:

  1. Uninitialized Constant Documentscontroller::Pdfkit >>>>> Download Now

    >>>>> Download Full

    Uninitialized Constant Documentscontroller::Pdfkit >>>>> Download LINK

    >>>>> Download Now

    Uninitialized Constant Documentscontroller::Pdfkit >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete