Monday, August 29, 2016

Deploying Rails application from archive | Fixed issues

Deploying Rails application from archive | Fixed issues


Deploying Rails application from archive

Posted: 29 Aug 2016 07:35 AM PDT

I need to deploy a new version of a Rails server to a machine that doesn't have access to its Git repository. What's the best way to do it? Is there anyway to deploy a Rails server (preferably using Capistrano) from a prepacked archive?

Capistrano overrides routes.rb

Posted: 29 Aug 2016 07:33 AM PDT

I have a problem: Always I ran cap production deploy Capistrano overrides my config/routes.rb to default rails code.

Rails.application.routes.draw do    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html  end  

Any idea?

Thanks in advance!

CapFile

require 'capistrano/setup'  require 'capistrano/deploy'  require 'capistrano/rails'  require 'capistrano/nginx'  require 'capistrano/puma'  require 'capistrano/puma/nginx'    Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }  

config/deploy.rb

lock '3.6.1'    set :application, 'demo-ror'  set :repo_url, '<my_git_repo>'  set :scm, :git  set :branch, :master  set :deploy_to, '/var/www/demo-ror'  set :tmp_dir, '/home/ubuntu/tmp'  set :pty, true  set :format, :airbrussh  set :format_options, command_output: true, log_file: 'log/capistrano.log', color: :auto, truncate: :auto  set :keep_releases, 5  set :keep_assets, 2  set :app_server, true  set :app_server_host, "127.0.0.1"  set :app_server_port, 8080    # nginx  ...    # puma  ...  

config/routes.rb

Rails.application.routes.draw do    root 'home#index'  end  

rails postgresql query regex length limit

Posted: 29 Aug 2016 07:38 AM PDT

I am making a rails app and I need to use long regular expressions in my queries. I found that in the Postgrssql is a 32 kilobyte limit on regular expression length. Here is how my query looks like, regex that I am using is around 1 million characters long

MyModel.where('model_field ~* ?', 'some very very long regex')  

But this query raises an error REG_ETOOBIG. How to increse regex length limit in the postgress or how to deal with the queries with very long regexes?

Permit array in params

Posted: 29 Aug 2016 07:25 AM PDT

I have the following JSON:

{      "name": "pizza",      "ingredients": [          {"name": "tomato", "amount": 3, "unit": "un"},          {"name": "chesse", "amount": 100, "unit": "gr"}      ]  }  

And I pass this JSON using POST to my controller, then I need to trust this paramters but I'm not be able to permit the array of hash ingredients.

How to permit it? I tried params.permit(:ingredients).permit(:name, :amount, :unit).to_h, but it doesn't work.

Trying to open .rb file but I get an error message "in '<main>'undefined local variable or method 'quit for main: Object (NameError)

Posted: 29 Aug 2016 07:11 AM PDT

I'm completely new to coding and just started 2 days ago but I'm sticking with it, it's really exciting to learn! I'm learning ruby first and the course gives me a folder of .rb files to follow along but I noticed when I double click the .rb file it opens command prompt but immediately closes every time. I looked up this issue and they said to find the path of the file in command prompt and open the file through command prompt directly instead, but when I navigate to the directory of the folder in command prompt and type "ruby (file name that is .rb)" then press enter I get that error message in the title. Why won't my command prompt open the .rb file even when doing so manually from command prompt when I have ruby installed?

An "yml" config file doesn't exist after deploying to heroku

Posted: 29 Aug 2016 07:03 AM PDT

Rails 3.2

On localhost it works, on heroku not:

# my_app/config/initializers/something123.rb  config_file = YAML.load_file("#{Rails.root}/config/my_data.yml")[Rails.env].symbolize_keys --  # ....................  

The error is

undefined method `symbolize_keys' for nil:NilClass (NoMethodError)".   

But the file is in the repo.

What is the best way to share a text file between cluster nodes?

Posted: 29 Aug 2016 06:51 AM PDT

The chef recipe creates a text file on one node which is the used by two other nodes. I am thinking of storing the text file in an encrypted data bag when it is generated on the first node. The encrypted data bag is then loaded on the 2 other nodes.

I am trying to use the following post as a reference: how to create\edit encrypted data bag item from a chef recipe

Please suggest if it is correct way to share the text file on 2 other nodes after it is generated on the 1st node.

Pubnub going to stuck after publish some messages

Posted: 29 Aug 2016 06:45 AM PDT

Pubnub going to stuck after publish some messages, it is working fine for some messages but stuck after a limit.

How to add price upon checking a check_box in Ruby on Rails

Posted: 29 Aug 2016 06:52 AM PDT

I am working on a paid ad job board, and am using #Payola-Payments (Implementation of Stripe Payment Processor with Rails Application) to charge each job post on the app..

This is what I like to do:

When a check_box is checked, I want the price the application will deduct to change from default set price in my Jobs table, to the addition of the check_box worth.

Pictorial explanation of what I like to do:

Upon checking the box, it's suppose to add $20 to my default price in jobs table.

My Job Post Form

schema.rb

Note: A price default of $200 in cents (i.e. 20000) is set in my jobs table. The reason being what is required in Payola-payments documentation. So anytime anyone posts job advert, $200 will be deducted from his/her credit card by Stripe.

ActiveRecord::Schema.define(version: 20160827065822) do       create_table "jobs", force: :cascade do |t|    t.string   "title",            limit: 255    t.string   "category",         limit: 255    t.string   "location",         limit: 255    t.text     "description"    t.text     "to_apply"    t.datetime "created_at",                                   null: false    t.datetime "updated_at",                                   null: false    t.string   "name",             limit: 255    t.integer  "price",                        default: 20000    t.string   "permalink",        limit: 255    t.string   "stripeEmail",      limit: 255    t.string   "payola_sale_guid", limit: 255    t.string   "email",            limit: 255    t.string   "website",          limit: 255    t.string   "company_name",     limit: 255    t.boolean  "highlighted"   end  end  

What I have done to solve this:

I defined a method inside my model (job.rb) called price_modification and called before_save on it, such that my model looks like this code below but didn't work:

class Job < ActiveRecord::Base      include Payola::Sellable    before_save :price_modification      def price_modification      price    end      def price_modification=(new_price)      if :highlighted == t        self.price += (price + 2000)      else        self.price = new_price      end    end    end  

Thanks in advance.

Am using Ruby 2.2.4 and Rails 4.2.5.1

rails each method reset in controller workaround

Posted: 29 Aug 2016 06:01 AM PDT

So i have this in my controller at the moment:

popular = Impression.select('impressionable_id, count(impressionable_id) as total').group('impressionable_id').order('total desc')  popular.each do |popevents|    @events = Event.where(id: popevents.impressionable_id)  end  

Basically all this is doing is selecting the most popular events that are saved in the impressions table and getting all the event information.

So in my view i have this:

  <% @events.each do |e| %>    <pre>      <%= e.eventname %>    </pre>    <% end %>  

I was expecting to see around 4-5 event names here, However i'm only seeing 1. I'm guessing its because the @events is getting reset?

What would be the work around for this?

Sam

MySQL Regular expressions: How to match digits in the string with \d?

Posted: 29 Aug 2016 06:14 AM PDT

I have a column release_date which stores date in a string format(Not in DATETIME format. Because they can be sometime any other string literals).

I want to find all the records based on given month and year but with any date.

Tried following but did not work for me,

> Post.find(:all, :conditions => ["release_date RLIKE ? AND deleted_at is null", "^\d{2}-01-2016"])  

When I try same thing with following by giving direct date, it works fine.

> Post.find(:all, :conditions => ["release_date RLIKE ? AND deleted_at is null", "09-01-2016"])  

Note:- I am using Ruby On Rails 2 and MySQL

Your help is much appreciated!

Want to schedule a task on every 2 hours from 8am to 12pm on heroku through scheduler add on

Posted: 29 Aug 2016 06:58 AM PDT

I want to create a task that run on every 2 hours from morning 8 to midnight. I have created task and tested locally , when i made a job through scheduler it just gives me three times daily , hourly and every 10 min. How can i customize it.

tests failing after change default timezone for activerecord

Posted: 29 Aug 2016 05:51 AM PDT

I have the following method:

def track(user)    user.last_login_from_ip_address = request.env['REMOTE_ADDR']    user.last_login_at = Time.zone.now    user  end  

and in my controller, I do this

track(user).save!

I also have the following test to make sure that the user is being tracked correctly:

  before do      @user = create(:user, password: 'P@ssw0rd1', email: 'right@email.com', activation_state: 'active')      @user.activate!    end    it 'should change the last login time' do      post :authenticate, params      expect(@user.reload.last_login_at).not_to be_nil    end  

until now, it was passing perfectly.
Now, I had to change the timezone in application.rb as follows:

config.active_record.default_timezone = 'Europe/Berlin'

after I added this line, this test is now failing. there is no last_login_at anymore set.
I found this behaviour very weird, and I have no idea what could be causing it

Rails/Sqlite 3 - Displaying table data on page

Posted: 29 Aug 2016 06:55 AM PDT

I'm very very very new to Rails, and I've got a fast approaching deadline to code my first rail app as part of a challenge.

I've so far created the basic blog application, to get my head around how rails works.

I need to display a list of all data held within a table on a page in my site. In blog, I've got an index page - which lists all blog posts so I've been trying to follow the same process.

I've created a populated table in my database, and a controller - but when I try and display info from that database on my page I get the following error:

uninitialized constant RecordsController::Aliens

class RecordsController < ApplicationController      def index          @records= Records.all      end  end  

All I want to achieve is a simple table, which has the list of my records in, so far I'm not having much luck retrieving the data from the database.

Any help appreciated!

How to create functional test for Ruby on Rails

Posted: 29 Aug 2016 05:36 AM PDT

What is the best way create tests that include:

  • set checkbox
  • bush buttom
  • etc.

for Ruby on Rails test environment?

Rails joining tables having has_many association

Posted: 29 Aug 2016 05:55 AM PDT

I have Student and Record table with a simple has_many :through association:

class Student < ActiveRecord::Base    has_many :records  end  

I need to fetch all students details of MBA branch. I need to assign result to a variable @students and need to access record of a student using

@students.each do |student|     students.records.each do |record|        ///     end  end  

That is I need to access has_many related class datas also into an object. How to write query for that. I am newbee in rails. Please help .Thanks in advance

Error sending emails with Rails 4 & Devise (connection refused, port 25)

Posted: 29 Aug 2016 05:40 AM PDT

I'be been having some massive issues getting emails to send. I've tried multiple ways of doing things; using gmail, mailgun, sendgrid, the mailgun gem etc, no luck at all. For some reason it's trying to send using port 25 although, as you can see below, I'm specifying port 587. The error I get is:

Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 25):

My development.rb file is as follows:

  config.action_mailer.default_url_options = { :host => 'localhost:3000' }    config.action_mailer.delivery_method = :smtp    config.action_mailer.perform_deliveries = true      config.action_mailer.smtp_settings = {    :address => 'smtp.mailgun.org',    :port => 587,    :api_key => 'key-5d321b99f722e71f759993ee41512b99',    :user_name => 'postmaster@sandbox3ed8de9510c845c68bf0d867a8f25394.mailgun.org',    :password => '(mailgun password)',    :domain => 'sandbox3ed8de9510c845c68bf0d867a8f25394.mailgun.org',    :authentication => :plain,    :enable_starttls_auto => true    }  

I have looked around for solutions however none seem to solve the issue. I'm totally out of ideas.

Add more markers to markerCluster without removing previous

Posted: 29 Aug 2016 05:11 AM PDT

I build a map and add markers. When I'm calling AJAX , Some more records are coming from db and updating the location to map without reloading the map. But the problem is it is making new cluster for new records. Here is code :

var marker, i;        var markers=[]        for (i = 0; i < locations.length; i++) {          marker = new google.maps.Marker({            position: new google.maps.LatLng(locations[i][1], locations[i][2]),            map: map,            icon: locations[i][4]          });              google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {            return function () {              infowindow.setContent("<img src="+locations[i][5]+" width='100%'><br> <strong>"+locations[i][0]+"</strong>");              infowindow.open(map, marker);            }          })(marker, i));            // assuming you also want to hide the infowindow when user mouses-out          marker.addListener('mouseout', function() {              infowindow.close();          });            google.maps.event.addListener(marker, 'click', (function (marker, i) {            return function () {              infowindow.setContent("<img src="+locations[i][5]+" width='100%'><br> <strong>"+locations[i][0]+"</strong>");              infowindow.open(map, marker);            }          })(marker, i));          markers.push(marker);        }          var markerCluster = new MarkerClusterer(map, markers,{             imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'          });  

Query in Ruby on Rails 4 to make a selection based on the current user

Posted: 29 Aug 2016 05:41 AM PDT

I am new to Ruby on Rails and try to make the right query. But after reading the documentation and examples I don't manage to get the right query out of it. So I hope someone can point me in the right direction.

Situation I build an app where trainers can setup trainings, and give these trainings on several dates (the dates are called thrills), other users can subscribe for these thrills. It has the following structure: models and needed table.

My models code looks like this:

class User    has_many :trainings    has_many :thrills, through: :reservations    has_many :reservations    class Training    belongs_to :user    has_many :reservations    has_many :thrills    has_many :users, through: :thrills    class Thrill    belongs_to :training    has_many :reservations    has_many :users, through: :reservations    class Reservation    belongs_to :user    belongs_to :thrill    has_one :training, through: :thrill  
  • On an index page I want to show all the thrills that the current user has setup sorted by date. I think I need a query that comes up with the table in the uploaded image, and from that table I can select all Thrills where current_user.id = user_id
  • On the search page I want to show only the trainings that have a Thrill that is not full (therefore I want to make a count of the Reservations)

I was thinking of something like this:

@thrills = Thrill.joins(:trainings).where('? = trainings.user_id, current_user.id')   

or

@thrills = Thrill.where('? = @thrill.training.user_id', current_user.id).all  

or

@thrills = Thrill.joins(:trainings).where(trainings: { user_id: current_user.id })  

But unfortunately none of them works. Does someone have an idea how to solve this? Thanks in advance!

Getting text only when nokogiri certain HTML structure

Posted: 29 Aug 2016 05:26 AM PDT

I've been struggling with nokogiri lib in order to fetch (scrape) content from web, I failed to understand how to get only text without nested tags. Here is what I parse

<div class="line1">text I need  <br><div class="podp_k">group:</div><a class="GR" title="go to this group" href="#" rel="?sectID=2">group 1</a>  <br>  <div class="podp_k">brand:</div><a class="BR" title="go to brand" href="#" rel="?sectID=0&amp;brand=16">China&nbsp;&nbsp;CHINA</a>  </div>  

Here is the way I scrape it

tagcloud_elements = nokogiri_object.css("div#products_tbody > table > tbody > tr > td > div.line1 > text()")  f.puts tagcloud_element.text.gsub(/^\s+/,'')  

the gsub at the end does almost exactly I need, but I lefts number of whitespaces after. Can anybody suggest the best way to get only "text I need" from the above example please?

Rails and MQTT: Subscribe to topic in background at server startup?

Posted: 29 Aug 2016 06:27 AM PDT

I want to subscribe to a mqtt topic in my rails app when the server starts and and keep the subscription always active and running.

I'm using this mqtt gem for mqtt communication: https://github.com/njh/ruby-mqtt

Here is what I have right now:

in application.rb:

config.after_initialize do   mqttSub = BackgroundMQTT.new   mqttSub.run  end  

BackgroundMQTT class:

class MQTTSubscriber    def run      Thread.new do        MQTT::Client.connect(:host => 'localhost', :port => 1883,) do |c|          c.get('#') do |topic,message|            puts "#{topic}: #{message}"            #Do things, access activerecord etc.          end        end      end    end  end  

So basically the mqtt subscription starts in the after_initialize method and as far as I know, doesn't stop automatically?

Also As you can see, I'm running the subscription in a Thread, otherwise my rails application would stop doing anything else than listening to the mqtt subscription.

This seems to work at least for the first couple of minutes.

I'm not sure if this is a recommended way of doing what I want to do. Could this cause any issues that I haven't considered? What would be a recommend way of doing this?

Rails/Stripe: No such token

Posted: 29 Aug 2016 05:41 AM PDT

I'm trying to create a one time, single charge in Stripe with Rails. I am getting the following error:

enter image description here

Stripe::InvalidRequestError (No such token: tok_18nnwSJ6tVEvTdcVs3dNIhGs)  

However, as can clearly be seen in the photo, the token is in the parameters. That token is from Stripe.js.

Here is my code in my controller:

  Stripe.api_key = "xxxxxxxxxxx"    customer = Stripe::Customer.create(source: params[:stripeToken])    charge = Stripe::Charge.create({    :amount => 10000,     :currency => "usd",    :customer => customer.id,    :description => "Example charge"  })  

I have also tried:

  Stripe.api_key = "xxxxxxxxxxx"    charge = Stripe::Charge.create({    :amount => 10000,     :currency => "usd",    :source => params[:stripeToken],    :description => "Example charge"  })  

And that does not work either. All of this is simple, boilerplate code straight from the Stripe site, any idea what I could be doing wrong? I'm not having any trouble with the Stripe embedded form.

Can't modify frozen hash. Rails 4.1 and SSE

Posted: 29 Aug 2016 04:42 AM PDT

I am trying to implement SSE in rails 4.1.16 with ActionController::Live. But I am consistently getting Can't modify frozen hash error. I am getting this error in development. The code is -

def continuous_printer_energy_data   response.headers['Content-Type'] = 'text/event-stream'   sse = SSE.new(response.stream, event: 'time')   begin    loop do      puts request.path      if(request.path == '/energy/printer/continuous')        sse.close        break      end      Energy.uncached do        a = Energy.last        sse.write({ :data => a })        sleep 1      end      end     rescue Exception => e    puts 'its a exception'    logger.error e.backtrace.join("\n")    sse.close     ensure    sse.close    end  

end

My error back trace is -

    RuntimeError - can't modify frozen Hash:    actionpack (4.1.16) lib/action_dispatch/middleware/cookies.rb:309:in `[]='    actionpack (4.1.16) lib/action_dispatch/middleware/cookies.rb:532:in `[]='    actionpack (4.1.16) lib/action_dispatch/middleware/session/cookie_store.rb:110:in `set_cookie'    rack (1.5.5) lib/rack/session/abstract/id.rb:350:in `commit_session'    rack (1.5.5) lib/rack/session/abstract/id.rb:226:in `context'    rack (1.5.5) lib/rack/session/abstract/id.rb:220:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/cookies.rb:562:in `call'    activerecord (4.1.16) lib/active_record/query_cache.rb:36:in `call'    activerecord (4.1.16) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'    activerecord (4.1.16) lib/active_record/migration.rb:380:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'    activesupport (4.1.16) lib/active_support/callbacks.rb:82:in `run_callbacks'    actionpack (4.1.16) lib/action_dispatch/middleware/callbacks.rb:27:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'    better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'    better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'    better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'    railties (4.1.16) lib/rails/rack/logger.rb:38:in `call_app'    railties (4.1.16) lib/rails/rack/logger.rb:20:in `block in call'    activesupport (4.1.16) lib/active_support/tagged_logging.rb:68:in `block in tagged'    activesupport (4.1.16) lib/active_support/tagged_logging.rb:26:in `tagged'    activesupport (4.1.16) lib/active_support/tagged_logging.rb:68:in `tagged'    railties (4.1.16) lib/rails/rack/logger.rb:20:in `call'    quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets'    request_store (1.3.1) lib/request_store/middleware.rb:9:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/request_id.rb:21:in `call'    rack (1.5.5) lib/rack/methodoverride.rb:21:in `call'    rack (1.5.5) lib/rack/runtime.rb:17:in `call'    activesupport (4.1.16) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'    actionpack (4.1.16) lib/action_dispatch/middleware/static.rb:84:in `call'    rack (1.5.5) lib/rack/sendfile.rb:112:in `call'    railties (4.1.16) lib/rails/engine.rb:514:in `call'    railties (4.1.16) lib/rails/application.rb:144:in `call'    rack (1.5.5) lib/rack/content_length.rb:14:in `call'    puma (3.6.0) lib/puma/configuration.rb:225:in `call'    puma (3.6.0) lib/puma/server.rb:578:in `handle_request'    puma (3.6.0) lib/puma/server.rb:415:in `process_client'    puma (3.6.0) lib/puma/server.rb:275:in `block in run'    puma (3.6.0) lib/puma/thread_pool.rb:116:in `block in spawn_thread'  

Thanks in advance for the help.

rails devise undefined method username when I want to use it with cancancan

Posted: 29 Aug 2016 07:22 AM PDT

I want to achieve a role based authorisation in rails. for login I use the gem devise, which works perfect. but after I am including some code of cancancan like in this tutorial I get an error undefined method username and when I remove username I get an error undefined method email...

here is my code:

ability.rb (to manage what a user with a specific role can do)

    class Ability      include CanCan::Ability      def initialize(user)          user ||= User.new         if user.role?(:admin)         can :manage, :all       elsif user.role?(:mitarbeiter)         can :manage, :documents         can :manage, :entries       end      end    end  

a part of my user.rb

      ROLES = {0 => :admin, 1 => :mitarbeiter}      attr_reader :role :      def initialize(role_id = 0)      @role = ROLES.has_key?(role_id) ? ROLES[role_id] : ROLES[0]      end      def role?(role_name)      role == role_name    end  

a part of my application_controller.rb

  protect_from_forgery with: :exception      check_authorization      rescue_from CanCan::AccessDenied do |exception|      flash[:warning] = exception.message      redirect_to root_path    end      private      def current_user      User.new(session[:id])    end      helper_method :current_user  

I really can't get whats wrong... I thought that I have to set @user like @role in user.rb but it doesn't helped

How to call rails api using parameter

Posted: 29 Aug 2016 04:29 AM PDT

I am trying to call api with parameter can anyone please help me to call the api with the parameter passed using user id and converted image. here is the code for controller which i tried so far:

base_encode=Base64.encode64(params[:Profile_Picture].read)                    puts base_encode                    api_response = HTTParty.post('http://52.41.99.60/GEMWebservices/MobileAppService.php?Service=EditProfile', :query => {:id=_@user.id,:base64_encode=>base_encode })                      @json_hash = api_response.parsed_response                      return @json_hash  

f.select not preselecting value while editing

Posted: 29 Aug 2016 07:10 AM PDT

I have a field state_id for which I am using select dropdown

= form.select :state_id, options_for_select(states), {}, prompt: 'Select State'  

but while editing the form it doesn't preselect the current value of state_id

I know I can pass :selected param to pass the default selected value

OR

options_for_select(states, @object.state_d)  

But as this guide suggest I don't need to use those options

Can anyone tell me what am I doing wrong?

NOTE: It's a nested attribute and other fields are working fine with f.text_field but not f.select

Ruby on Rails - Show only 3 image pr page

Posted: 29 Aug 2016 07:07 AM PDT

In my application, I have Post & Slide models. A Post has many slides.

Currently, in my posts#show view, I show all the slides that belongs to a post.

How can I show only 3 slides per page and have a Next & Prev button to next group?

Example: A post has 20 slides, It only show 3 slide per page with a Next button to the next 3 etc and the URL would for instance be domain.com/p/posts-title/ps/1, domain.com/p/posts-title/ps/2 etc.

This is what I have done now:

  1. Created with_pagination action in posts_controller
  2. Added it to my route
  3. Created the with_pagination view

in with_pagination view

- @post.slides.order('sort_order ASC').each_slice(4) do |group|  

in routes

resources :posts, path: 'p' do      get 'ps/:page', to: 'posts#with_pagination', as: :xyz      // i have other stuff here  end  

in controller

def with_pagination      @post = Post.find_by_slug(params[:post_id])  end  

Now I can show all the slide on that page, but as mentioned I only want to show 3 slides pr page with a next and prev link to them.

Ps: I have had almost the same question before but it doesn't work as the same since other one was with use of pagination and pagination is not what I am looking for

Send email out after new employee registered by overriding Devise Registrations controller

Posted: 29 Aug 2016 07:27 AM PDT

Rails 4.2 Devise

I would like to send out a welcome email to newly registered employees.

I have the following overridden Devise Registrations Controller:

class Employees::RegistrationsController < Devise::RegistrationsController    layout 'dashboard', only: [:new]    # Only allow admin employees to add new employees    before_action :authenticate_employee!, :redirect_unless_admin,  only: [:new, :create]      # Removes the already logged in issue with Devise    skip_before_action :require_no_authentication       def create     super     EmployeeMailer.welcome_email(resource).deliver_now if resource.valid?    end        private      def sign_up_params      params.require(:employee).permit(:first_name, :last_name, :email, :password, :password_confirmation, :paypal_email, :mobile, :skype_id, :address,:province_state, :country, :postal_code, :bachelor_degree, :os, :status, role_ids: [])    end      def account_update_params      params.require(:employee).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password, :paypal_email, :mobile, :skype_id, :address, :province_state, :country, :postal_code, :bachelor_degree, :os, :status, role_ids: [])    end      def redirect_unless_admin      unless current_employee && current_employee.is_super_admin?        redirect_to root_path, alert: "Only authorized ProvenWord Employees are permitted to register new employees."      end    end       def sign_up(resource_name, resource)      true    end  end  

This works, however I don't think its correct as I have to test if the resource is valid otherwise the system tries to send out emails even for submissions with invalid data.

Is this the correct way of doing this or how should I make sure only a resource that is saved to the database will be used to send out an email?

ajax call to changes drop down on basis of other drop down rails

Posted: 29 Aug 2016 03:44 AM PDT

I have followed this approach to change one drop down on the bases of other (ajax based).

In index.slim I have

= search_form_for [:club,@q], as: :event_query do |f|      .row        .col-sm-3           = f.select :event_id_eq, options_from_collection_for_select(Event.where(event_type: :event ,allow_seatings: true), "id", "name", @q.event_id_eq),{prompt:'All Events'},{class:'form-control event_search btnselect'}         .col-sm-2            = f.select :seating_id_eq, options_from_collection_for_select(Seating.all, "id", "name", @q.seating_id_eq),{prompt:'All Seatings'},{class:'form-control btndefault'}  

and ajax call is like

$("#event_query_event_id_eq").change(function(){          var url = '/club/event/rsvps/seating_change?event_id_eq=' + $(this).val() + ''          $.ajax({            url: url,            dataType: 'html',            type: 'POST',            success: function(data){            $("#event_query_seating_id_eq").html(data); }          })        })  

I have also created seating_change.js.erb

<% if @seatings.present? %>      <%= select_tag 'event_query_seating_id_eq', options_from_collection_for_select(@seatings, "id", "name") %>  <% else %>      <%= select_tag 'event_query_seating_id_eq', '' %>  <% end %>  

and in Controller

def seating_change      if params[:event_id_eq].present?        @seatings = Seating.where(:event_id => params[:event_id_eq] )        respond_to do |format|          format.js { render layout: false }        end      end    end  

If I try to alert in success of ajax call it has the data which I desire for but the second drop down remains same.

What 'm I doing wrong

Send xlsx file to front end - AngularJS

Posted: 29 Aug 2016 07:38 AM PDT

I want to send xlsx file created by rubyXL gem to front end, which is AngularJS. When I save worksheet in a stream and send it by send_data method, I get the data, but I can't open the created document because it is broken.

workbook = RubyXL::Workbook.new  worksheet = workbook[0]  worksheet.sheet_name = 'Average of Team'  worksheet.add_cell(0, 0, 'A1')  buffer = workbook.sream  send_data buffer  

I am able to save the data to disk. But I can't be able to send it to client side. so, that I can access the data from angularjs.

workbook = RubyXL::Workbook.new  worksheet = workbook[0]  worksheet.sheet_name = 'Average of Team'  worksheet.add_cell(0, 0, 'A1')  path = "#{Rails.root}/tmp/#{Time.now.strftime('%Y%m%d%H%M%S%L')}.xlsx"  workbook.write(path)  send_file path  

I don't want to save the workbook on cloud and send a link to the client side. What is the best solution of my problem? Where I make mistake?

UPD: It seems when I trying to send saved file, I delete file before sending completes.

UPD: When I am sending data, I have problems with encoding data. I tried to use string.bytes.to_a.pack("C*"), string.force_encoding('binary'). But it didn't help me.

No comments:

Post a Comment