Friday, October 21, 2016

Unable to restart rails Delayed Job on system reboot using cron | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Unable to restart rails Delayed Job on system reboot using cron | Fixed issues


Unable to restart rails Delayed Job on system reboot using cron

Posted: 21 Oct 2016 08:35 AM PDT

I'm using Ubuntu 14.04.4 LTS

Crontab:

SHELL=/bin/bash  @reboot ~/Projects/MyAPI/startworkers.sh;  

startup script:

# /Projects/MyAPI/startworkers.sh    #!/bin/bash  source /home/server-linux/.bashrc    cd ~/Projects/LucyAPI    # Start background workers  bin/delayed_job --pool=tracking:2 --pool=emailverify:6 start  

I expect there to be 6 delayed jobs running after reboot. However, none of them start. However, if I manually execute start.sh everything works as expected.

What am I doing wrong?

change_column in Rails 4 and Rail 5

Posted: 21 Oct 2016 08:37 AM PDT

It's possible rollback a migration with change_columns in rails 4 or rails 5 with:

def change  end  

Should I use up and down methods instead?

How can I run npm on my Rails app on Heroku?

Posted: 21 Oct 2016 08:27 AM PDT

I just introduced npm modules into my Rails app (locally) and have been trying to deploy it to Heroku. I recall reading that if I have a package.json file at the root directory of my app, Heroku would detect it and run npm install upon build. My assets, however, are apparently not being installed (for example, webpack). How can I make this work?

Rails - Search for object based on association's value

Posted: 21 Oct 2016 08:40 AM PDT

I've got two models Company and InsuredObject. Company has_many InsuredObjects and the reverse belongs_to. Currently, I have a functioning search for InsuredObject(s) that returns all objects that contain the search input as shown below:

# /models/insured_objects.rb    def self.search(search)    query = "%#{search}%"    if search      where("object LIKE ? OR insurance_type LIKE ? OR class_code LIKE ? OR information LIKE ?",           query, query, query, query)    end  end  

and:

# /controllers/insured_objects_controller.rb    def index    @insured_objects = InsuredObject.search(params[:search])  end  

Each Company has a is_active attribute. I'm trying to think of a way to search for the same thing but only return InsuredObject(s) that their Company's is_active attrutbute is true. Any thoughts?

Bootstrap not being properly applied

Posted: 21 Oct 2016 08:31 AM PDT

I was just recreating a project that I began on nitrous.io (instagram clone) at my mba. But the bootstrap its not working, just the colors (on the button).

enter image description here

The button is coloring but the shape remains not rounded.

The project: https://github.com/TheBigTester/PhotoBuzz The page: http://localhost:3000/posts/new

Ps: The project from nitrous.io works good, no prob with the bootstrap, I already checked everything but no visible differences between both projects, and I dont really know what do.

How to use sort_by or order_by on view and controller with will_paginate?

Posted: 21 Oct 2016 08:29 AM PDT

In my rails application I am limiting the amount of rooms displayed on a page through pagination, I want to allow the user to order/sort the results to different columns of the room model. I think I will need a drop down menu to do this, and then pass this data over to my rooms_controller maybe through an instance variable.

How can I sort the rooms with the select tag according to a column and what do I need to do in the corresponding controller to make this work?

At the moment I am using this for a drop down menu:

index.html.erb

...  ...  <%= will_paginate @rooms %>    <div id="order-by">       <select>          <option value="asc">Distance</option>          <option value="asc">Name</option>          <option value="asc">Price (low to high)</option>          <option value="des">Price (high to low)</option>          <option value="asc">Reviews</option>        </select>  </div>  

rooms_controller.rb

...  ...    def index      @rooms = Room.paginate :page => params[:page], :per_page => 12    end  ...  

My room model has listing_name:string, address: string, nightly_price:integer and has_many reviews. My review model belongs_to room. I am using geocoder gem for the location of an room.

I have searched allot and tried multiple things to make this work and I can not figure this one out. For any hints on how to solve this I would be really happy! If you need further information just let me know.

Initializing script via Turbolinks, display map with Gmap4rails

Posted: 21 Oct 2016 08:04 AM PDT

I'm trying to initialize my script with turbolinks, following this post : rails 4 with turbolinks and window load . I don't really know how to do it, considering my ruby tags.. do you know how I should do? here is my code :

<script src="//maps.google.com/maps/api/js?key=[mykey]"></script>  <script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>  <script src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript'></script> <!-- only if you need custom infoboxes -->  <h1> Points de vente </h1>  <div style='width: 800px;'>    <div id="map" style='width: 800px; height: 400px;'></div>  </div>  <script type="text/javascript">  handler = Gmaps.build('Google');  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){  markers = handler.addMarkers(<%=raw @hash.to_json %>);  handler.bounds.extendWith(markers);  handler.fitMapToBounds();  });  </script>

Thanks!

is Node.js or python using django or ruby on rails better and more secure for developing back-end for webapps that are going to be used heavily

Posted: 21 Oct 2016 08:05 AM PDT

I understand that all back-end languages are secure and the security actually depends on the implementation of the language.

I am a new programmer, I need to start on a cross-platform project that is going to be used heavily by a lot of people and the deadline for the project is in 6 months from now.

Till now I developed my websites' back end using php but I realised that there were a lot of ways I could leave my websites vulnerable for attacks so I am looking to switch to a new back-end language.

I am currently looking at Node.js, Python(using django), Ruby(on rails). which one of these would help me develop more secure back end for webapps while not compromising, if not at all, much on the scalability given the fact that I donot have much experience and chances of wrong implementations exist.

I would also like to mention that I know python(OOP concepts, but dont know how to use it for making web-apps) and basic javascript but I have no base in ruby, but I wouldn't take into consideration that i dont know ruby as I am ready to learn it and besides ruby is said to be pretty easy to learn.

I would also like to know if I can use angularjs with all of these languages or if I can use it only with Node.js.

and when you are answering, could you also take into consideration job oppurtunities.

Thanks a lot for your answers.

Gem wicked pdf - CSS doesn't work with rails 5

Posted: 21 Oct 2016 08:31 AM PDT

I just upgrade my application to rails 5 and the gem wicked pdf doesn't display css anymore. I changed nothing, so there're may be some specifications with rails 5. If anybody figure out this problem feel free to help :)

Here is my code :

object_controller

def download      @object = object.find(params[:object])      respond_to do |format|        format.html        format.pdf do          render pdf:          "ptf_#{@object.id}",                 layout:       'layouts/pdf_layout',                 template:     'objects/download.html.erb',                 title:        "download object",                 show_as_html: false,                 header: { content: render_to_string(template: 'objects/header_pdf.pdf.erb'), spacing: 7  },                 footer: { content: render_to_string(template: 'objects/footer_pdf.pdf.erb'), spacing: 10 },                 margin: { top: 55, bottom: 35 }        end      end  

pdf_layout.html.erb

<% content_for :title do %><%= @title %><% end %>  <meta http-equiv="content-type" content="text/html; charset=utf-8" />  <%= wicked_pdf_stylesheet_link_tag 'pdf' %>  <br>  <%= yield %>  

I tried with both helpers wicked_pdf_stylesheet_link_tag and stylesheet_link_tag wicked_pdf_asset_base64

header_pdf.html.erb

<div class="center">        <%= image_tag wicked_pdf_asset_base64("logo.png"), class: 'header' %>        <div class="first-class"><%= @object.title %></div>        </div>  

This is a few extract of my code just to show you how I organize my file generation. I also have a file pdf.scss

Rails has_many through implementation

Posted: 21 Oct 2016 07:35 AM PDT

working on a project using Ruby on Rails, I'm facing some issues.

I have 5 models: Employee, Macaddress, Vlan, Visit, Visitor

Each employee has from 0 to n macaddresses and a macaddress belongs exactly to one employee.
Each Vlan has from 0 to n macaddresses and a macaddress belongs exactly to one Vlan.

Now my problem is between Employee, Visit and Visitor because I need to implement it as a ternary relation in matter of database, so I decided to use has_many through.

Here my models:

Employee:

class Employee < ActiveRecord::Base      has_many :macaddresses,   dependent:      :destroy    has_many :visits,         dependent:      :destroy    has_many :visitors,       :through    =>  :visits    end  

Macaddress:

class Macaddress < ActiveRecord::Base        belongs_to :employee        belongs_to :vlan  end  

Vlan:

class Vlan < ActiveRecord::Base    has_many :indirizzimacs  end  

Visit:

class Visit < ActiveRecord::Base      belongs_to          :employee      belongs_to          :visitor  end  

Visitor:

class Visitor < ActiveRecord::Base      has_many :visits,       :dependent      :destroy      has_many :employees,    :through    =>  :visits  end  

Now my two main questions:

#1

Given this (macaddress_params is a function using require and permit):

class MacaddresssController < ApplicationController      def create      @macaddress = current_employee.macaddresss.build(macaddress_params)      [...]      else       @macaddresss = current_employee.macaddresss.all      end    end  

I know I could do the same in VisitsController (same relation), but how could I do the same in VisitorsController?

#2

Given this:

@employee = Employee.find(params[:id])  @macaddress = current_employee.macaddresss.new  

I can do the same such as:

@visit = current_employee.visits.new  

But how can I do the same for the visitor?

Thank you a lot in advance!

JQuery File Upload: sending two request on data.submit()

Posted: 21 Oct 2016 07:34 AM PDT

I am trying to Upload videos in my app using Paperclip and jquery-fileupload-rails

I followed ulpoad file with paper clip and jquery to upload video, but was uploading video just as I select the video and don't wait for pressing submit button, So I followed 1: jQuery file upload: Is it possible to trigger upload with a submit button? to select a single video and upload it on submit button, not on selecting file.

But There is issue on whether I put submit button in the form or outside form.

When I put the submit button in the form than it sends two requests to pressing submit button, one with Video and second one without Video.

And If I put button outside form that it sends one request on pressing submit button but after successful create/update it remains on the same page.

All I wanted is that on pressing Submit, sending just one request and redirect to index page on successful create/update.

In _form.slim

= simple_form_for [:admin,add] do |f|     .wizard-content       .row         .col-sm-6            = f.input :video, multiple: false, wrapper: :horizontal_file_input            button#submit_button.btn.btn-primary              | Save  

In adds.coffee

 jQuery ->        $('#add_video').attr('name','add[video]')        $('#add_video').fileupload           $('#submit_button').off('click').on 'click', ->             data.submit()  

In controller I have

def create       if add.save         redirect_to admin_adds_path         flash[:success]= "Add Created"       else         render :new       end     end       def update       if add.update(add_params)         redirect_to admin_adds_path         flash[:success]= "Add Updated"       else         render :edit       end     end  

there is also a _add.slim

= image_tag(@add.uploaded_file(:small), class: 'thumb')  

I also created create.js.erb and edit.js.erb as suggested tutorial I followed (though, I didn't understand its use )

- if @add.new_record?    |  alert('Failed');  - else    |  if ($('h1') !== undefined) { $('h1').append("    =j render partial: 'adds/add', locals: { add: @add }    | "); }  

Whats wrong with this?

Savon ignores namespace_identifier attribute

Posted: 21 Oct 2016 07:26 AM PDT

Am trying to re-write written by savon body namespace - ins0 I have this client variable:

client = Savon.client(wsdl: "https://integcert.synxis.com/interface/Contracts/ChannelConnect2004.wsdl", log_level: :debug, log: true, pretty_print_xml: true, env_namespace: :soapenv, namespaces: {"xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:head": "http://htng.org/1.1/Header/","xmlns:ns": "http://www.opentravel.org/OTA/2003/05"}, convert_request_keys_to: :none, namespace_identifier: "ns", element_form_default: :qualified)  

And when Am doing the request:

client.call(:ping, soap_header: { "head:HTNGHeader": { "head:From": { "head:Credential": { "head:userName": "******", "head:password":"*****" }}}}, message: {"ns:EchoData": "TestData"})  

I've got this soap rq body:

    <soapenv:Body>      <ins0:OTA_PingRQ>        <ns:EchoData>TestData</ns:EchoData>      </ins0:OTA_PingRQ>    </soapenv:Body>  

Where this ins0 is came from?

Also when I tried to define client with namespace_identifier: nil parameter and did this kind of request:

client.call(:ping, soap_header: { "head:HTNGHeader": { "head:From": { "head:Credential": { "head:userName": "******", "head:password":"*****" }}}}, message: {"ns:OTA_PingRQ": {"ns:EchoData": "TestData"}})  

I've got this soap rq body:

 <soapenv:Body>  <OTA_PingRQ>    <ns:OTA_PingRQ>      <ns:EchoData>TestData</ns:EchoData>    </ns:OTA_PingRQ>  </OTA_PingRQ>  

And the correct body that I want to have is:

<soapenv:Body>        <ns:OTA_PingRQ>     <ns:EchoData>TestData</ns:EchoData>     </ns:OTA_PingRQ>  </soapenv:Body>  

Any ideas how to remove additional nested OTA_PingRQnode or replace ins0 namespace by the custom ?

What can a language like RoR or PHP really do? [on hold]

Posted: 21 Oct 2016 07:15 AM PDT

Are these languages just to execute scripts such as registering, login and stuff like that in a web? Let me explain myself:

I want to build a web application where the users (through the browser ofc) can get a consecutive number which is stored in memory.

Let's say we have u1, u2 and u3. Then u1 gets two numbers, he'd get 1 and 2. Then u2 gets 4 numbers, he'd get 3, 4, 5 and 6. Finally u3 gets 1 number, it'd be 7. They can choose how many numbers to get.

So my question is, as that number is increasing, I think it'd better to store it in memory rather than in a db. So my questions are:

  • Can this be done using RoR or PHP or any other similar language to store that number in memory? If not tell me what they're for, just scripts stuff like I mentioned at the beginning?

  • Or would I have to use a server program to store that number in memory using something like java, Python, etc. If so, which language would you recommend?

Sorry if this sounds too noobish but I'm getting into the web programming world.

Cheers and thanks.

Restore a table using pg:backups restore

Posted: 21 Oct 2016 07:07 AM PDT

Reading Heroku postgres documentation just came across this:

Unlike with the previous pgbackups commands, you cannot restore a partial backup into an existing database. When you run pg:backups restore, all data is deleted from the target database before restoring the backup.

source 1 source 2

is there a way to restore a single table using pg:backups restore?

Rails - How to assign booking numbers to events

Posted: 21 Oct 2016 06:54 AM PDT

I'm building an events app using Ruby on Rails. Events can be either free or paid. In each instance I want to be able to assign a unique booking number for users when they book their places on an event. What do I need to do to ensure both paid and free events are assigned a number in the server and a booking is then confirmed? Is it as simple as adding a booking_number column in my bookings table?

This is my model and controller code -

booking.rb

      class Booking < ActiveRecord::Base        belongs_to :event      belongs_to :user        #validates :quantity, presence: true, numericality: { greater_than: 0 }      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?            # We can always set this, even for free events because their price will be 0.          #self.total_amount = booking.quantity * event.price                    # 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_pennies * self.quantity                          charge = Stripe::Charge.create(                              amount: total_amount,                              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           

No comments:

Post a Comment