Monday, December 12, 2016

Polymorphism ignored by mongoid | Fixed issues

Polymorphism ignored by mongoid | Fixed issues


Polymorphism ignored by mongoid

Posted: 12 Dec 2016 07:45 AM PST

In a nutshell

I run into the following error with validations / model saving

NameError (uninitialized constant PolymorphicAssociation):

Full Background & class code

I am trying to implement a referral system. I want to keep a separate Referral class to be able to store additional referral information (such as referral context/UTM, etc.)

class User  class Referral  

On the user side it begins quite simple : the following module is included into User

module User::Referrable    extend ActiveSupport::Concern      included do      include Mongoid::Token        # A user can refer may others      has_many :referrals_initiated, class_name: 'Referral',        inverse_of: :referrer      has_many :referees, class_name: 'User',        inverse_of: :referrer        # A user is referred by one guy      has_one :referral_received, class_name: 'Referral',        inverse_of: :referees      belongs_to :referrer, class_name: 'User',        inverse_of: :referees  

My app supports many user profiles. For instance

module User::Profileable # included in User    has_one :admin_profile    has_one :employee_profile    module UserProfile    belongs_to :user    class AdminProfile    include UserProfile    class EmployeeProfile    include UserProfile  

Note that I don't have a base class UserProfile so I can manage collections of Admins, Employees in MongoDB

Now things are getting nasty. I want to keep track of which UserProfile referred which other UserProfile. So I have to fight with polymorphism

First the extension for the Referral model

class Referral    ...    belongs_to :referrer_profile, polymorphic: true,      inverse_of: :referrals_initiated      counter_cache: true    belongs_to :referee_profile, polymorphic: true,      inverse_of: :referral_received      validates_presence_of :referee_profile, :referrer_profile  

And the profile extension (included in UserProfile)

module Profile::Referrable    extend ActiveSupport::Concern      included do      # A profile can refer may others      has_many :referrals_initiated, class_name: 'Referral',        inverse_of: :referrer_profile      # Impossible to have polymorphic has_many ! Go through the referral only      # has_many :referee_profiles, polymorphic: true        # A profile is referred by one profile      has_many :referral_received, class_name: 'Referral',        inverse_of: :referree_profiles      belongs_to :referrer_profile, polymorphic: true,        inverse_of: :nil # Cannot have a polymorphic inverse        delegate :referees, :referrer,        to: :user, allow_nil: :true    end  end  

So far so good, but then I get the following problem : when I validate the Referral model, I run into

NameError (uninitialized constant RefereeProfile):

How do I screen for integers that are too big in my Rails model?

Posted: 12 Dec 2016 07:38 AM PST

I'm using Rails 4.2.7 with PostGres 9.5. I have this column in my Rails migration ...

my_num               | integer                     |   

In my model, I would like to screen for numbers that are too big and set them to nil. For instance, the number "659722222222222" is getting set on my model and is causing the below error

Error during processing: (RangeError) 659722222222222 is out of range for ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer with limit 4  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/type/integer.rb:45:in `ensure_in_range'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/type/integer.rb:23:in `type_cast_for_database'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/quoting.rb:13:in `quote'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:641:in `block (2 levels) in values_sql_for_columns_and_attributes'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each_with_index'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `map'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:631:in `block in values_sql_for_columns_and_attributes'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:630:in `map'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:630:in `values_sql_for_columns_and_attributes'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:530:in `import_without_validations_or_callbacks'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:490:in `import_with_validations'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:417:in `import_helper'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-import-0.16.1/lib/activerecord-import/import.rb:331:in `import'  /Users/davea/Documents/workspace//app/services/abstract_import_service.rb:161:in `block in save_my_object__time_results'  

Rather than save the model, I would like to set the field to nil only if it is set to an integer value that is too big for PostGres SQL. How do I do this?

Note, I do NOT want to change teh column type of the PostGres column. You didn't think this was going to be that easy, did you?

Why the server boots up multiple sidekiq processes? How to put them down?

Posted: 12 Dec 2016 06:52 AM PST

I deployed a rails app with puma(3.4.0) and sidekiq(3.0.2). Almost all of the configrations are default value by capistrano-puma and capistrano-sidekiq. But I don't know why multiple sidekiq processes turned up and occupy the memory.

Screenshot of htop: enter image description here

Sidekiq has concurrency feature so that i only want one sidekiq process. Any help with this? Thanks in advance!

How to build own class with behavior like ActiveRecord_Relation

Posted: 12 Dec 2016 06:51 AM PST

Please look on example for understanding what I mean:

        class UserPlaces        def initialize(user, country)          @base_query = user.places.where(contry_id: country.id)        end          def with_positive_rating          @base_query = @base_query.joins(:place_ratings).where('place_ratings.value > 0')            self        end          def order_by_name          @base_query = @base_query.order('places.name ASC')          self        end          def filter_by_group(group)          @base_query = @base_query.joins(:group).where(groups: { id: group.id })          self        end          def fetch          @base_query        end      end    

In this case I can use:

        UserPlaces.new(user, country).with_positive_rating.fetch      UserPlaces.new(user, country).with_positive_rating.order_by_name.fetch      UserPlaces.new(user, country).filter_by_group(group).order_by_name.fetch        ...  

I want to do the same but without "fetch" method. Something like using scope for model instance.

Anybody know how I can do that?

Thanks.

Ruby on Rails db migrate error while loading the hoe gems

Posted: 12 Dec 2016 06:18 AM PST

I have been having this problem the whole day. whenever i try to do a rake db:migrate command on rails i keep getting this error. "error while loading the hoe gem. Please install it by running the following: $ [sudo] gem install hoe".

But everytime i run and update all my gems i still get the same error. The hoe gems i have already installed is the latest version (hoe 3.15.3) Please help. Am running rails 5.0.0.1this is the error i keep getting

Modifying migration column not loaded in migration rails

Posted: 12 Dec 2016 07:23 AM PST

I added two migration which in the first one I add a column to a model, and in the second one, I execute a function that stores a value into the column recently added of some rows.

The problem is that when I run rake db:migrate the second migration throws an error because the first migration was loaded but the database hasn't changed yet, so one approach is to run the command twice (it works).

First Migration :

class AddRegisteredReportToSpecialOfferUse < ActiveRecord::Migration    def up      add_column :special_offer_uses, :registered_report, :boolean, default: false    end      def down      remove_column :special_offer_uses, :registered_report    end  end  

Second Migration :

class CreateReportsFromMigrations < ActiveRecord::Migration    def change      OneClass.perform    end  end  

the OneClass.perform is a method that makes an update of the attribute added previously

def perform  ´´´  special_offer_uses.update_attribute(:registered_report, true)  ´´´  end  

The error thrown :

StandardError: An error has occurred, all later migrations canceled: undefined method `registered_report=

Note that the method undefined is the name of the attribute added previously.

I wonder if there is a way to avoid running the command twice without throwing any error.

Why postgres calculate percentage wrong (based on columns result)

Posted: 12 Dec 2016 05:37 AM PST

I am trying to get % of discount between two columns, first problem which i was solved is that other column may be 0 or null, Now when I calculate it it always give me 100 or 0 as a result of column 'discount'

Product.active.select("*, 100-(price/(  (CASE WHEN(market_price IS NULL OR market_price = 0)  THEN price ELSE market_price END)))*100   AS discount")  

All the results was 0 or 100 :\

Tried to solve with sub function but still gave me same wrong percentage.

underscores are converted into hypens in rails headers?

Posted: 12 Dec 2016 07:19 AM PST

Hi I have restful apis in rails and react-redux at front-end..

At front-end:

axios.defaults.headers.access_token = "default values"  axios.defaults.headers.some_header_token = "some value"  

i.e I have sent two parameters from client-side

  1. access_token
  2. some_header_token

What I'm Getting at rails server

At my console I'm getting

 request.header["access_token"] = nil   request.header["some_header_token"] = nil  

but getting values in

request.header["access-token"]  request.header["some-header-token"]  

underscores are getting converted into hypens

I have one php theme with all files of .php extension now i want this all in .html extesnion to integrate to my ruby on rails project. any solution ? [on hold]

Posted: 12 Dec 2016 04:38 AM PST

I have one php theme with all files of .php extension.Now i want this all in .html extension to integrate to my ruby on rails project. any solution ? As, how to convert php theme to html theme ?

How to check if a date of a booking is overlapping rails hotel application

Posted: 12 Dec 2016 06:20 AM PST

I'm making a web application in Ruby on Rails for a hotel. I've seen some questions around that may look the same as mine, but I couldn't find the right solution.

A user can create a booking and choose which room they want and what day they are arriving and leaving. Everything is working as the way I want except of the fact that my rooms can be booked with overlapping dates.

Schema:

create_table "bookings", force: :cascade do |t|    t.integer  "user"    t.integer  "course"    t.date     "arriving_date"    t.date     "leaving_date"    t.boolean  "breakfast"    t.text     "remarks"    t.datetime "created_at",    null: false    t.datetime "updated_at",    null: false    t.integer  "room_id"    t.integer  "user_id"    t.index ["room_id"], name: "index_bookings_on_room_id", using: :btree    t.index ["user_id"], name: "index_bookings_on_user_id", using: :btree  end    create_table "rooms", force: :cascade do |t|    t.string   "room_number"    t.integer  "room_type_id"    t.datetime "created_at",   null: false    t.datetime "updated_at",   null: false    t.index ["room_type_id"], name: "index_rooms_on_room_type_id", using: :btree  end  

Controller

  def new      @booking = Booking.new    end      def create      @booking = Booking.new(booking_params)      if @booking.save        redirect_to @booking      else        flash[:notice] = "Something went wrong"        render 'index'      end    end  

Model of booking

class Booking < ApplicationRecord    belongs_to :room    belongs_to :user  end  

What I want

When a user tries to create a booking they should not be able to choose a certain room that is already booked at the days they want to sleep in the hotel.

Rails 5 Unpermitted Parameter Upon Save

Posted: 12 Dec 2016 04:29 AM PST

I'm working with two models Submission and Tag. Submission has_one :tag. In my controller I have set up my submission_params as follows:

params.require(:submission).permit(:domain, tag_attributes:[:tag_text, :notes])  

However, I'm getting the error: Unpermitted parameter: tag

From my log:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"BEJZXOERC3cGSZFlAL91kRJgR+YFcHd6+yMYilDyu/NyN1YviwahKwrifAQfWMdu53/NYCnOVD4NHNXSZmPk7Q==", "submission"=>{"domain"=>"test", "tag"=>{"tag_text"=>"test tag", "notes"=>"test"}}, "commit"=>"Submit"}  

Perhaps I'm just rusty and am overlooking something or does rails5 have a new trick to dealing with strong params? Thanks in advance!

Opentok streaming not showing on the client's end

Posted: 12 Dec 2016 04:06 AM PST

I'm currently studying Ruby on Rails and would like to create a live video session. I've followed through a tutorial I found but I only managed to have the video available for the one who is streaming (/users/:id/streams/:id), but not the ones who are watching (/users/:id/streams/:id/view). Here are the codes I've included for this feature:

Stream Class

class Stream < ActiveRecord::Base    before_create do |stream|      session = OPENTOK.create_session      stream.opentok_session_id = session.session_id    end      belongs_to :user    has_many :views  end  

View Class

class Watch < ActiveRecord::Base    belongs_to :user    belongs_to :stream  end  

Stream Controller

class StreamsController < ApplicationController      def new      @stream = Stream.new    end      def create      params.permit!      @stream     = current_user.stream || current_user.create_stream      @stream.update(params[:stream])      redirect_to user_stream_path(@stream.user, @stream)    end      def show      @stream = current_user.stream      gon.opentok = opentok_data(@stream)    end      private      def opentok_data(stream)      token = OPENTOK.generate_token(stream.opentok_session_id)      { sessionId: stream.opentok_session_id, apiKey: Figaro.env.opentok_api_key, token: token }    end    end  

View Controller

require 'opentok'    class ViewsController < ApplicationController        def index          @stream = User.find(params[:user_id]).stream          gon.opentok = opentok_data(@stream)      end    private      def opentok_data(stream)      token = OPENTOK.generate_token(@stream.opentok_session_id)      { sessionId: stream.opentok_session_id, apiKey: Figaro.env.opentok_api_key, token: token }  end  

Stream View

<%= javascript_include_tag "//static.opentok.com/webrtc/v2.2/js/TB.min.js" %>  <h1>Your stream</h1>  <h3><%= @stream.desc %></h3>  <div id="publisher"></div>  <%= link_to "Watch", user_stream_views_path(current_user.id, @stream.id) %>  

Viewer's View

<%= javascript_include_tag "//static.opentok.com/webrtc/v2.2/js/TB.min.js" %>  <h1><%= @stream.user.email %></h1>  <h3><%= @stream.desc %></h3>  <div id="stream"></div>  

Routes

  resources :users, only: [:index, :new, :show, :edit, :update, :destroy] do       resources :streams, only: [:new, :create, :show] do        resources :views, only: [:index]      end    end  

Stream Coffeescript

$ ->    if $('#publisher').length      # Initialize an OpenTok Session object      session = TB.initSession(gon.opentok.sessionId);        videoOptions = {width: 640, height: 480}        # Initialize a Publisher, and place it into the element with id="publisher"      publisher = TB.initPublisher(gon.opentok.apiKey, 'publisher', videoOptions);          # Attach event handlers      session.on        # This function runs when session.connect() asynchronously completes        sessionConnected: (event) ->          # Publish the publisher we initialzed earlier (this will trigger 'streamCreated' on other clients)          if session.capabilities.publish == 1            session.publish(publisher)          else            return        # Connect to the Session using the 'apiKey' of the application and a 'token' for permission  session.connect(gon.opentok.apiKey, gon.opentok.token);  

View Coffeescript

$ ->    if $('#stream').length      # Initialize an OpenTok Session object      session = TB.initSession(gon.opentok.sessionId);        videoOptions = {width: 640, height: 480}        # Attach event handlers      session.on        streamCreated: (event)->          # Subscribe to the stream that caused this event, put it inside the container we just made          session.subscribe(event.stream, $('#stream')[0], videoOptions);        # Connect to the Session using the 'apiKey' of the application and a 'token' for permission  session.connect(gon.opentok.apiKey, gon.opentok.token);  

Somehow the coffeescript for the view is not loading and I'm not sure why. Any help on this would be greatly appreciated. Thanks!

Put text in helper method, but the caluclation is in float

Posted: 12 Dec 2016 04:22 AM PST

Hi I have a helper method for some calculations, I want to put some text but when I call this method the after calculation is in float. I want to put text how can I do this?

if m == e     0.0   elsif e == 0    put "not defined"       else    (m - e)/e   end  

Any idea? thanks!

When installing elasticsearch and running the Searchkick's reindex command, do I need to be inside the master branch?

Posted: 12 Dec 2016 04:51 AM PST

Should I be inside the master branch when installing Elasticsearch and running the rake searchkick:reindex command?

Because all the tutorials I found are inside the master branch, but when I'm adding a feature to my app, I always checkout on other branch and just merge it if the feature works.

How to develop and deploy Angular2/Rails application(integrate Angular2 with Rails)?

Posted: 12 Dec 2016 03:41 AM PST

Now I'd like to use Angular2 to develop the frontend, and use Ruby on Rails to develop the backend. I know I can create a Rails app using RubyMine IDE, and create an Angular2 app according to the documentation from angular. But how should I integrate the Angular2 app with the Rails app. How do I modify the Rails source to include the Angular2 source.

This link just changed HeroService to hit Rails app at http://localhost:3001.

Someone said I must convert .html file to .html.erb file, put them in the app\views folder and put .css, .ts files on app\assets folder. Is that correct? If so, how should I add the Angular2 source into the Rails source? or tell me where I can find some excellent documentation about this topic.

bxslider isn't displaying images until page resize with responsive design

Posted: 12 Dec 2016 07:22 AM PST

I am trying to implement bxslider on a responsive page (using Bootstrap) and for the first 2 or 3 times it is showing images correctly. However after that it just shows a narrow white band:

enter image description here

If I resize the browser then the bxSlider resizes correctly and displays the images.

My partial code contains the following code (Note, this populates a div as a result of an AJAX call)

<ul class="product-view-bxslider">    <% @product.images.each do |image| %>        <li><%= image_tag image.image.url %></li>    <% end %>  </ul>    <script>    $(document).ready(function(){      console.log('slider initialising');      $('.product-view-bxslider').bxSlider({        onSliderLoad: function(){          console.log('finished loading');        }      });    });  </script>  

The bxslider setup is working correctly as I do always get the expected output to console.

I have replicated this behaviour in Safari, Chrome and Firefox.

From my searches most people who have had resize issues with bxslider were having issues when resizing the browser, not on initial load.

Edit

Setting an initial fixed height for the layout of the bxslider displays all images at once (including 2 extra - which I assume are for buffering the navigation). Again only a browser resize forces the bxslider to resize and display correctly.

.bx-viewport.bx-viewport {    min-height: 90px;  }  

enter image description here

This is suggesting that perhaps the issue isn't, as I originally believed, a result of misbehaving with responsive layouts.

Perhaps the following information is pertinent to this question. I am using Rails and the page I posted earlier is a result of an AJAX invocation of ProductsController#show action. There doesn't appear to be anything esoteric going on here:

ProductsController#show

  def show    end  

show.js.erb

  $('#product-details').html("<%= escape_javascript(render 'products/show') %>")  

_show.html.erb

as posted at start of question

invocation

<%= link_to 'Show', product, remote: true %>  

Ruby: starting thin as deamon returns Bad File Descriptor

Posted: 12 Dec 2016 03:17 AM PST

Starting the Ruby thin client works fine in command line:

RAILS_ENV=production bundle exec thin --ssl-disable-verify -C services/private_pub/private_pub_thin.yml start  

But starting it as deamon returns a Bad File Descriptor:

user@app:~/app$ RAILS_ENV=production bundle exec thin -d --ssl-disable-verify -C services/private_pub/private_pub_thin.yml start  user@app:~/app$ /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:149:in ``': Bad file descriptor (Errno::EBADF)      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:149:in `block in git'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/shared_helpers.rb:72:in `call'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/shared_helpers.rb:72:in `with_clean_git_env'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:149:in `git'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/source/git/git_proxy.rb:83:in `version'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/env.rb:78:in `git_version'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/env.rb:22:in `report'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:74:in `request_issue_report_for'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:40:in `log_error'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:100:in `rescue in with_friendly_errors'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors'      from /opt/rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/exe/bundle:19:in `<top (required)>'      from /opt/rbenv/versions/2.2.1/bin/bundle:23:in `load'      from /opt/rbenv/versions/2.2.1/bin/bundle:23:in `<main>'  

Any idea? This happened without any code change. There is also nothing already running.

capybara visit url with reserved character

Posted: 12 Dec 2016 03:13 AM PST

I want to visit a url returned from an API. Url looks like this: http://domain/#CollectionPlace:{\"id\":\"2101612070000671031\"}

When I call visit on this Capybara returns bad URI(is not URI?):(URI::InvalidURIError) error. I have tried to manually tried URI.encode(url) and URI.encode(UR.parse(url) but looks like I need to retain the # in the url for it to work.

How do I make it work?

search bar using MaterializeCss and Ruby on Rails

Posted: 12 Dec 2016 03:06 AM PST

I have this form for searching:

 = form_tag(posts_path, :method => "get", id: "search-form") do      = text_field_tag :search, params[:search], placeholder: "Search Posts"      = submit_tag 'Search'  

how can i make something like that: search_bar ?

Check if record exists where child has value

Posted: 12 Dec 2016 03:24 AM PST

I'm building an interface where people can submit tags for the content of various websites so each Submission has a parameter domain and has_one :tag.

The trick is that I would like to check to see if that tag has previously been submitted for that domain before saving.

Something like:

Submission.where(domain: submission_params[:domain], tag.tag_text: submission_params[:tag][:tag_text]).exists?  

What is the difference between these two line.? [duplicate]

Posted: 12 Dec 2016 02:55 AM PST

This question already has an answer here:

I am not able to find the difference between these two line. If anyone know please clear this. Thanks in advance.

scope :not_deleted_auctions, -> { where(:is_deleted => false) }  scope :not_deleted_auctions, lambda { where(:is_deleted => false) }  

Getting the oldest datas from a table that are older than a 100 days

Posted: 12 Dec 2016 03:33 AM PST

I've been struggling with the following problem:

EXPLAINING

I have a table called part_subhourly_data that holds production data for a part (For the purpose of the problem, no need to know what a part is).

I need to archive the any data older than a 100 days. But since there's a lot of data (they arrive each 5 or 10 minutes) and we have more than 1000 parts, I need to do it the 5 oldest days each time.

This is the schema of my table:

part_subhourly_data    id INTERGER,     part_id INTEGER,     produced_at TIMESTAMP    data HSTORE  

So basically I need to get all data that is in this table, where produced_at is prior to 100 days ago and limit that to the first 5 days, per part.

Example:

Part 1 has data from 15 Aug 2016 until 12 Dec 2016 Part 2 has data from 1st Sep 2016 until 12 Dec 2016

100 days ago would be 3 Sep 2016.

For Part 1 I would take data from 15 Aug 2016 until 19 Aug 2016 (5 days). For Part 2 I would take data from 1st Sep 2016 until 3 Sep 2016 (3 days because of the 100 days old condition).

WHAT HAVE I TRIED

Well, I'm using rails on this, but a SQL solution is welcome as well. For now, What I'm doing is to grab the oldest data with:

SELECT "part_subhourly_data"."part_id", MIN(produced_at) produced_at    FROM "part_subhourly_data"    WHERE (produced_at < (NOW() - INTERVAL '100 days'))    GROUP BY "part_subhourly_data"."part_id"  

And then I loop Over each part_id and grab the data based on the MIN(produced_at). It works, but it doesn't seems ideal. I'm sure that there is some SQL magic to make it simpler, and quicker, without having to loop over each part.

Any idea?

how to keep secrets.yml, so as to build my raills app by semaphoreci.com?

Posted: 12 Dec 2016 07:14 AM PST

I created my rails app. Then I didn't know , but I need to add secrets.yml to .gitignore and I put it to my repository. I joined the rails app to semaphoreci.com. When I committed semaphoreci.com builded ok. Later I removed secrets.yml from my repozitory. I did:

git rm --cached config/secrets.yml  git rm -r --cashed .  git add .  git commit -m "anything"  

Now semaphoreci.com don't works. I got:

rake aborted!  Devise.secret_key was not set. Please add the following to your Devise initializer:      config.secret_key = 'my_key'  

I think,it happens becouse repo don't contain secrets.yml. I read that I need to keep secrets.yml outside repo. How to keep secrets.yml for semaphorecy?

I tried to use dotenv gem, but I think that if I will add to .gitignore .env file and will add secretts.yml to my repository with code:

development:  secret_key_base: ENV['secret_key_base']  

but I think semaphorecy will not build, becouse in repo ENV['secret_key_base'] will find .env file, or not? I don't understand, how can I store my secret_key_base in repository so as to semaphoreci can find it and launch rails server.

Rails Oauth2 authorization modify

Posted: 12 Dec 2016 02:48 AM PST

Recently, I want to implement an authentication system that allow other companies create bunch of users in our service.

I read many references about Oauth2 flow like this. enter image description here

But I think my authentication system now would not contain the step (B), (C) and (D).

However, I think in far future, my service should surpport 3rd party access, which means I need the step (B) to (D).

My question is that, is there a greater implementation that match my first require? Is there a easier way to scale authentication system?

BTW I use Rails to create this backend system.

Ruby On Rails Website Using Schema Diagram

Posted: 12 Dec 2016 02:19 AM PST

I am learning ruby on rails. I want to build a website for the below schematic diagram: Schema. What are the steps I should follow to build it ?. A tutorial online with schematic diagram would help. I want to know:

1) How to give primary and foreign keys ( I am using sqlite database) ?

2) How to give associations ?

3) How to query ?

Thanks guys for the help.

extract single cases from array

Posted: 12 Dec 2016 02:48 AM PST

An array of records being generated by

@signatures = Signature.where('action_id IN (?)', @actions).all  

will have actions with one or more signatures.

Signature id: 1, action_id: 1  Signature id: 2, action_id: 2  Signature id: 3, action_id: 1  Signature id: 4, action_id: 3  Signature id: 5, action_id: 2  

What ruby instruction can extract just the single cases, based on action_id? Signature.id = 4 in the above example

Rails (Puma & Passenger) can't find bundled gems after deploying with Capistrano

Posted: 12 Dec 2016 01:51 AM PST

I've been working through the PragProg Agile Rails 5 book. I'm hung up on the deployment. I did a straight copy/paste deploy locally with Apache. When I deployed with Capistrano, however, the deployment completes without error, but running passenger or rails s in the current release directory fails immediately, saying that it can't find the listen gem. Any clue what could be triggering this?

I've ran bundle package and bundle --deployment. Neither helped. I'm not sure what the dirs are supposed to look like with Capistrano, but the vendor/cache gems aren't in the current dir, even though they're in the development directory.

Here's the what I got in the production.log.

  D, [2016-12-12T18:47:37.353437 #12570] DEBUG -- :   [1m[35m (0.2ms)[0m  [1m[34mSELECT DATABASE() as db[0m  D, [2016-12-12T18:47:37.353879 #12570] DEBUG -- :   [1m[35m (0.2ms)[0m  [1m[34mSELECT GET_LOCK('2754433143543187260', 0);[0m  D, [2016-12-12T18:47:37.365473 #12570] DEBUG -- :   [1m[36mActiveRecord::SchemaMigration Load (0.5ms)[0m  [1m[34mSELECT `schema_migrations`.* FROM `schema_migrations`[0m  D, [2016-12-12T18:47:37.375988 #12570] DEBUG -- :   [1m[36mActiveRecord::InternalMetadata Load (0.5ms)[0m  [1m[34mSELECT  `ar_internal_metadata`.* FROM `ar_internal_metadata` WHERE `ar_internal_metadata`.`key` = 'environment' LIMIT 1[0m  D, [2016-12-12T18:47:37.379731 #12570] DEBUG -- :   [1m[35m (0.2ms)[0m  [1m[35mBEGIN[0m  D, [2016-12-12T18:47:37.380950 #12570] DEBUG -- :   [1m[35m (0.2ms)[0m  [1m[35mCOMMIT[0m  D, [2016-12-12T18:47:37.381305 #12570] DEBUG -- :   [1m[35m (0.2ms)[0m  [1m[34mSELECT RELEASE_LOCK('2754433143543187260')[0m  

Apache just says "Incomplete response received from application" when I visit http://localhost:8080. I already made sure a secret key was set correctly.

Storing periodicity in Rails

Posted: 12 Dec 2016 04:37 AM PST

I am giving users an option to receive, say, emails at a periodicity of their choice, for example:

Every day at 5am  

or

Every Friday at 11pm  

or even

Every second Monday of the month at 12am  

What would be my best choice for storing this kind of data in order to feed it to Whenever gem?

Update

I was able to solve the question with @mudasobwa 's advice in combination with the cron_parser gem. The process flow is:

  • Get user's input from a select box on the frontend
  • Parse it on the backend and de-code into cron format (e.g. 7 would mean that I will need to send emails every week, so the code could be "1 1 * * 1"), store the value as periodicity.
  • Use the cron_parser gem to generate the next_run dateformat which is used to tell whenever gem which jobs it needs to perform that are dated.

Validation for date/times that overlap

Posted: 12 Dec 2016 01:57 AM PST

In my rails app I have a model called Booking. Users can book by selecting a date and then selecting a time.

Currently, I have a validation that checks whether the date and time combination already exists, and if it does then it raises an error.

The problem I am having is that each booking lasts for a certain time period, say 4 hours. Obviously I cant have a user booking at 8.30am, and another one at 9am, although my validation currently allows that.

I want to be able to check:

  • Is the date and time combination taken
  • Is the new booking being made while a different booking is taking place.

For example,

A user books for 2016/12/20 at 8.30am. The booking lasts for 4 hours.

Another user tries to book for 2016/12/201 at 10am, but because the booking is in the range of 8.30am-12.30am (4 hours), then it doesn't get validated.

This is my validation method currently:

def booking_available      errors.add(:date, "and time is not available") unless Booking.where("? = date AND ? = time", date, time).count == 0  end  

This is another one I have tried, although it only checks for the end of the booking period:

def booking_available      errors.add(:date, "and time is not available") unless Booking.where("? = date AND ? = time + interval ?", date, time, (bookingtime.to_i.to_s + 'h')).count == 0   end  

The date column corresponds to the date of the booking, time corresponds to the time and the bookingtime corresponds to the length/period of the booking.

How am I able to check whether the new booking is in the range of other bookings and their times?

Two different show views for restful resource in rails

Posted: 12 Dec 2016 01:36 AM PST

I have a job app with two kinds of (not-authenticated) users, referrers and candidates.

Currently I have 1 jobs controller and model.

Basically, I want to have two routes:

job/1 # jobs#show for referrers  j/1   # jobs#show for candidates  

Both routes are public, there are no logged-in users.

While the model data (=content) is very similar for the two routes, the views are obviously different. I am struggling to create two different show views within the same controller.

I have looked at setting up a separate namespace (seems to be for the entire controller), specific get routes or setting up a separate controller, but really not sure what the best "Rails" way is.

Any suggestions would be really helpful, thanks in advance!

No comments:

Post a Comment