Saturday, November 12, 2016

Docker - run two processes in single container | Fixed issues

Docker - run two processes in single container | Fixed issues


Docker - run two processes in single container

Posted: 12 Nov 2016 07:48 AM PST

I've created Ruby on Rails project with Nginx. Rails app and Nginx runs in separate and linked containers. This configuration works fine. However...

1) Is it possible to run both together (Rails / Puma server + Nginx) in a single container?

2) How should the CMD command in Dockerfile look like?

3) What command should I use as the "command:" attribute in docker-compose.yml?

I think that configuration to run them in separate containers is better solution, but I would like to get to know all possibilites.

I use Puma as a Rails' app server and to run it I use command: bundle exec puma -C config/puma.rb

Serialize nested attributes in Rails?

Posted: 12 Nov 2016 07:44 AM PST

So I have models like this:

  • folder, up_file has 1 chat_room
  • chat_room belongs to crmable with polymorphic: true (so 1 chat_room may belongs to folder or 1 up_file)
  • chat_room has many comments
  • comment belongs to chat_room and user (who posted the comment)

I've defined all relationship like this:

class Folder < ApplicationRecord      has_one :chat_room, as: :crmable, dependent: :destroy  end    class UpFile < ApplicationRecord      has_one :chat_room, as: :crmable, dependent: :destroy  end    class ChatRoom < ApplicationRecord      belongs_to :crmable, polymorphic: true        has_many :comments, dependent: :destroy      has_many :users, through: :comments  end    class Comment < ApplicationRecord      belongs_to :chat_room      belongs_to :user  end  

This setup worked fine with my web app. However, I'm writing API for this app, and I can't get that nested associations serialized with this gem

https://github.com/rails-api/active_model_serializers  

I've follow their tutorial here but my associations not rendered.

class FolderSerializer < ActiveModel::Serializer        attributes :id, :name, :ancestry, :creator_name #... my other attributes        has_one :chat_room, include: [ :id, comments: :user ]      # ^ I tried to serialize folder's chat_room with all it comments, along with these comments' users.  end  

All I got is this - chat_room association not serialized?

enter image description here

How to cache page with single dynamic block in Rails 4

Posted: 12 Nov 2016 07:44 AM PST

I need to cache the home page of my website. It's all static, but with dynamic user state block on top. If user is not logged in, then he sees log in link, otherwise name and balance. For this reason we can't simple cache whole page. What the way can I go?

  1. Cache whole page and add user state block after with AJAX;
  2. Use fragment cache of whole page without this block;
  3. Your version...

How to config my nginx to a running container with rails using raspian?

Posted: 12 Nov 2016 07:07 AM PST

I would like to run a container and config my nginx on my rasp pi 2 to expose my rails app to public.

How can bind nginx on my raspian with a container?

Pass results from loop into a form_tag

Posted: 12 Nov 2016 06:41 AM PST

In my ruby on rails application, I am trying to take results from an API (OMDBapi) call (response in JSON) and then display the results in a view. This is working as expected. In this case its a list of movie titles, the year it was made and the omdbID. I am try to take the omdbID value from the result and place that into a button that will call another method (which does a different API call to OMDB) to provide the rating of that specific movie that the user selected.

At the moment I am unable to get the button to provide any action, even though I believe I have my route configured correctly. Below is a part of my view. The results show correctly, and I get a button next to each result. But the button does nothing.

    <% @responsealltitles.each do |result| %>      <td><%= result["Title"] %> </td>      <td><%= result["Year"] %></td>      <td><%= result["imdbID"] %></td>        <td><%= submit_tag("Search for Rating") %>       <%= label_tag(:find_rating, "Show Movie Rating") %>      <%= form_tag( "findrating", method: "post") do %></td>  

Here is my routes entry

    match 'findrating', to: 'info#inforated', via: [:get, :post]  

Any thoughts what is wrong here? I am a beginner at coding, and at ruby.

Permit custom created params in rails

Posted: 12 Nov 2016 06:44 AM PST

I have already gone through following posts, without getting any satisfactory answers:

can't permit custom params with strong parameters

Permit extra params in special cases with Strong Params in Rails 4

What I want is to permit my custom created params in rails controller:

MY CODE

Template

= form_tag ...    = select_tag :hour, options_for_select(options_for_hours), name: "clinic_hour[close_time][]", title: "Hours"    = select_tag :minute, options_for_select(options_for_minutes), name: "clinic_hour[close_time][]", title: "Minutes"    = select_tag :convention, options_for_select([["AM", "AM"], ["PM", "PM"]]), name: "clinic_hour[close_time][]"    = submit_tag ...  

The above code creates params like:

Parameters: {"clinic_hour"=>{"close_time"=>["0", "0", "AM"]}}  

But in controller...

Controller

When I do like:

def clinic_hour_params    params.require(:clinic_hour).permit(      :close_time    )  end  

It still says this, in rails server log:

Unpermitted parameters: close_time  {}  

What's wrong?

Rails Model Calculation Only If Condition Met

Posted: 12 Nov 2016 07:09 AM PST

I have an item model and need to calculate the total profit less any fees. I am currently doing that right now in the model. However, I want to be able to have that calculation run only once the boolean is updated to sold. I've tried an if statement in the model, but that didn't work.

item.rb

class Item < ActiveRecord::Base    def profit_calc      sold_for - bought_for - fees - shipping rescue 0    end      def self.purchase_total      sum(:bought_for)    end      def self.fee_total      sum(:fees)    end      def self.shipping_total      sum(:shipping)    end      def self.sales_total      sum(:sold_for)    end      def self.profit_total      sum(:sold_for) - sum(:bought_for) - sum(:fees) - sum(:shipping)    end      scope :visible, -> { where(sold: false) }    scope :sold, -> { where(sold: true) }  end  

schema.rb

create_table "items", force: :cascade do |t|    t.string   "description"    t.float    "bought_for"    t.float    "sold_for"    t.float    "fees"    t.float    "shipping"    t.datetime "created_at",                          null: false    t.datetime "updated_at",                          null: false    t.boolean  "sold",                default: false  end  

statistics.html.erb

<td><%= number_to_currency(@items.profit_total) %></td>  

Community engine and AWS s3 for photo uploads

Posted: 12 Nov 2016 05:50 AM PST

I`m trying to configure the community gem to use s3. The docs say only: You'll need to change your configuration in your application_config.rb to tell CommunityEngine to use s3 as the photo backend.

Anyone knows what and how to change? Do I need any additional gems, config files?

How do I save the scraped data from Nokogiri to a rails model database?

Posted: 12 Nov 2016 05:21 AM PST

I want to save the scraped data to the database so that I can implement search and sorting functionality on it. I tried creating a new rake task and updating attributes but for that I need to run rake fetch-data every time the data is scraped. Anyway it didnt work. Is there any other way to achieve this? I m new to rails. Any help would be much appreciated. Thank You.

app/controller

def show    url = @scrapper.url     data = Nokogiri::HTML(open(url))    @doc= data.css(".s-item-container")  end  

app/views/show

 <% @doc.each do |item| %>     <tr>       <td><%= item.css(".s-access-title").text %></td>       <td><%= item.css(".s-price").text %></td>       <td><%= item.css("span+ .a-text-normal").text %></td>     </tr>   <% end %>  

The data I m getting

Devise Google+ authentication

Posted: 12 Nov 2016 05:21 AM PST

Im not sure what Im doing wrong with Rails 5 + devise ominauth authentication. Sigup form redirects to google+ and ask for permission, than I see only blank registration form on site. However, on the back end data is parsed and stored in my Identity model.

How do avoid this and create user without password?

devise.rb

  config.omniauth :google_oauth2, "xxxx.apps.googleusercontent.com", "xxx", scope: "email,profile,offline", prompt: "consent", setup: true  

routes.rb

  devise_for :users, :controllers => {sessions: 'users/sessions', registrations: 'users/registrations', passwords: 'users/passwords', omniauth_callbacks: "users/omniauth_callbacks"}, :path_names => { :sign_in => 'login' }  

omiauth_controller

  def google_oauth2      generic_callback( 'google_oauth2' )    end      def generic_callback( provider )      @identity = Identity.find_for_oauth env["omniauth.auth"]        @user = @identity.user || current_user      if @user.nil?        @user = User.create( email: @identity.email || "" )        @identity.update_attribute( :user_id, @user.id )      end        if @user.email.blank? && @identity.email        @user.update_attribute( :email, @identity.email)      end        if @user.persisted?        @identity.update_attribute( :user_id, @user.id )        # This is because we've created the user manually, and Device expects a        # FormUser class (with the validations)        #@user = FormUser.find @user.id        @user = User.find @user.id        sign_in_and_redirect @user, event: :authentication        set_flash_message(:notice, :success, kind: provider.capitalize) if is_navigational_format?      else        session["devise.#{provider}_data"] = env["omniauth.auth"]        redirect_to new_user_registration_url      end    end        def setup      request.env['omniauth.strategy'].options['scope'] = flash[:scope] || request.env['omniauth.strategy'].options['scope']      render :text => "Setup complete.", :status => 404    end  

Identity

class Identity < ApplicationRecord    belongs_to :user    validates_presence_of :uid, :provider    validates_uniqueness_of :uid, :scope => :provider      def self.find_for_oauth(auth)      identity = find_by(provider: auth.provider, uid: auth.uid)      identity = create(uid: auth.uid, provider: auth.provider) if identity.nil?      identity.accesstoken = auth.credentials.token      identity.refreshtoken = auth.credentials.refresh_token      identity.name = auth.info.name      identity.email = auth.info.email      identity.nickname = auth.info.nickname      identity.image = auth.info.image      identity.phone = auth.info.phone      identity.urls = (auth.info.urls || "").to_json      identity.save      identity    end  end  

User model

class User < ApplicationRecord    has_many :identities, dependent: :destroy      devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable,           :omniauthable, :confirmable, :lastseenable, :omniauth_providers => [:facebook, :google_oauth2]        def self.from_omniauth(auth)        where(provider: auth.provider, uid: auth.uid).first_or_create do |user|          user.email = auth.info.email          user.password = Devise.friendly_token[0,20]          user.first_name = auth.info.name   # assuming the user model has a name          user.profile_photo = auth.info.image # assuming the user model has an image        end      end      def self.new_with_session(params, session)      super.tap do |user|        if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]          user.email = data["email"] if user.email.blank?        end      end    end      def facebook      identities.where( :provider => "facebook" ).first    end      def facebook_client      @facebook_client ||= Facebook.client( access_token: facebook.accesstoken )    end      def google_oauth2      identities.where( :provider => "google_oauth2" ).first    end      def google_oauth2_client      if !@google_oauth2_client        @google_oauth2_client = Google::APIClient.new(:application_name => 'HappySeed App', :application_version => "1.0.0" )        @google_oauth2_client.authorization.update_token!({:access_token => google_oauth2.accesstoken, :refresh_token => google_oauth2.refreshtoken})      end      @google_oauth2_client    end    end  

joins from belongs_to where query not working

Posted: 12 Nov 2016 05:18 AM PST

I have been trying joins from the has_many table and i'm able to get it like Order has_many order_items

Order.joins(:order_items).where(order_items: {name: 'something'})  

But if i try from belongs_to table like

OrderItem.joins(:order).where(order: {value: 'something'})  

I tried searching with keyword belongs_to, joins i wasnt able to get it

Ruby modulus. Why are these two sums printing different answers?

Posted: 12 Nov 2016 05:57 AM PST

I'm learning ruby and having problems with the %Modulus sums.

puts "example #{101 % 4}"  

The above prints 1 in the terminal which is what I expected.

Why does the below print 101 in the terminal? Surely it's the same as above?

puts "example #{100 + 1 % 4}"  

I understand that % is just another way of saying 'X divided by Y with J remaining". Therefore surely the 2nd example should also return 1?

Any help will be greatly appreciated.

Change name of the named route in Rails 5

Posted: 12 Nov 2016 03:05 AM PST

I have a following routes.rb

resources :authors do    resources :books, only: [:create, :read] do      post "read"    end  end  

I would like to have the named route to be read_authors_books, but it gets generated as authors_books_read, is there a way to change the named route?

I have tried post "read" as: :read_authors_books but it generates it as authors_books_read_authors_books

Posting on Facebook page using Koala with automatic renewal of auth code

Posted: 12 Nov 2016 02:47 AM PST

I am using Rails 4 and have a working system to post on three different Facebook-PAGES using Koala. The only problem is that I have the Koala API auth codes hard coded into initializers and I need to renew them every 60 days (sometimes earlier). I have read, and re-read, every SO-question as well as the documentation but get none the wiser.

I do NOT have any users logging into the website through Facebook or anything like that. This is all handled as a rake, posting excerpts of my blog posts on my Facebook-page.

I have the following information (all tokens, ID's etc are examples):

- My application ID: my_app_id #=> 12343423423749274734  - My application secret: my_app_secret #=> fc2323cdf2ce2312cdc121efed212  - Page id for first Facebook Page (of three): fb_page1_id #=> 343395105021155  

With this I can create a Koala-Oauth connection:

oauth = Koala::Facebook::OAuth.new(my_app_id, my_app_secret, "http://www.mywebsite.com")  

by which I can get an app_access_token:

oauth.get_app_access_token #=> 1231231726347364273|VhfeSDf43JdsdfJsERFE  

This is, however, a dead end to me. I can't use this for anything.

If I go to https://developers.facebook.com/tools/explorer I can get an access token for my application that looks something like this:

tmp_token = "EAADaSDASDAMZBoBEBADBDuAqvgUYJPe7sJ5qmgoF3N1awXR4VTET3FYzXFZAPz0jLAoo8d4aaASd9BBZAp9aWbHB2xEvjFbo5At8ekuwyhFDCKbP0m4OYWmbM9GjSfq2KibjASDASDGAAHZCLIVmjWf2JQwj0N0VWBytI2eiswZDZD"  

by which I can create the rest:

base_connection = Koala::Facebook::API.new(tmp_token)  page_1_token = base_connection.get_page_access_token(fb_page1_id)  page_1_api = Koala::Facebook::API.new(page_1_token)  page_1_api.put_connections("me", "feed", message: "Test")  

...which successfully posts "Test" to my Facebook Page.

The problems I have now are:

  • I need to manually renew the tmp_token in my initializer every 30-60 days, which is the problem I need to get away from.
  • I don't understand how to get from the oauth.get_app_access_token to tmp_token. Basically, I can't create a tmp_token automatically in my rake-function.

I realize it could have to do with using:

oauth.url_for_oauth_code  

to get the code variable as a GET and then use

oauth.get_access_token(code)  

Is this the right (only?) way to go?

I tried the code I got in my adress field and input it into oauth.get_access_token(code) in my console but got an error: "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request [HTTP 400]" when I did that.

So, now I am very confused how to proceed.

How can I either:

  • renew my tmp_token on a frequent basis so I don't end up with expired a token?
  • OR, create a tmp_token in my rake-function?

Deadlock while bulk inserts in Postgres

Posted: 12 Nov 2016 05:01 AM PST

PG::TRDeadlockDetected: ERROR: deadlock detected\nDETAIL: Process 5449 waits for ShareLock on transaction 1712360; blocked by process 1325.\nProcess 1325 waits for ShareLock on transaction 1712346; blocked by process 5449.\nHINT: See server log for query details.\nCONTEXT: while inserting index tuple (663142,4) in relation "contacts"\n:

Getting deadlock while performing concurrent bulk inserts on table Contact. This table also has unique constraint on column phone. Also there are parallel reads on this table.

Query on which deadlock occurs is

INSERT INTO contacts (phone, name, email, external_id, created_at, updated_at) VALUES #{values} ON CONFLICT DO NOTHING;

where values is list of tuples(phone, name, email, external_id, created_at, updated_at) of size 300 to 400.

Primary key of this table is uuid and default value is gen_random_uuid()

Self association in rails to keep track of related records

Posted: 12 Nov 2016 02:04 AM PST

I have a model named Letter and an other one named LetterTracking :

class Letter < ApplicationRecord    has_many :letter_trackings, as: :trackable  end  

and:

class LetterTracking < ApplicationRecord      belongs_to :letter      has_many :letter_trackings, as: :trackable   end  

this is my create table migration for Letter Tracking:

class CreateLetterTrackings < ActiveRecord::Migration[5.0]    def change      create_table :letter_trackings do |t|        t.integer  :trackable_id, default: 0, null: false, unique: true        t.string   :trackable_type        t.text     :paraph        t.string   :status        t.string   :assignee        t.belongs_to :letter        t.timestamps      end    end  end  

as you can see in below screen shots when I select a tracking record for the second tracking the relation is ok but when ever I add the third letter tracking the second one relation removes and the last one keeps the association. What I want is to keep the letter tracking in each record not by the last one. I mean some thing like nested records in which I can keep the related records. any Idea ? Thank you enter image description here enter image description here

Template::Error (Undefined mixin 'border-radius'.):

Posted: 12 Nov 2016 02:58 AM PST

I am getting this error while adding a bootstrap template in my rails app:

ActionView::Template::Error (Undefined mixin 'border-radius'.):      2: <html>      3: <head>      4:   <title>Zunosys</title>      5:     <%= stylesheet_link_tag    'application', media: 'all', 'data-turboli  nks-track' => true %>      6:   <%= javascript_include_tag 'application', 'data-turbolinks-track' => tr  ue %>      7:   <%= csrf_meta_tags %>      8: </head>    app/assets/stylesheets/_accordion.scss:6:in `border-radius'    app/assets/stylesheets/_accordion.scss:6    app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_ht  ml_erb___752436248_72006156'  

my application.css.sass

/*   * This is a manifest file that'll be compiled into application.css, which will include all the files   * listed below.   *   * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,   * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.   *   * You're free to add application-wide styles to this file and they'll appear at the bottom of the   * compiled file so the styles you add here take precedence over styles defined in any styles   * defined in the other CSS/SCSS files in this directory. It is generally better to create a new   * file per style scope.   *   *= require_tree .   *= require_self   */    @import "bootstrap-sprockets"  @import "bootstrap"  

my application.html.erb

<!DOCTYPE html>  <html>  <head>    <title>Zunosys</title>      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    <%= csrf_meta_tags %>  </head>  <body>    <%= yield %>    </body>  </html>  

my accordion.scss

/* Accordion  ----------------------------------------------------------*/    .panel-group .panel {      @include border-radius(0);  }    .panel {      @include box-shadow(none);  }    .panel-heading {      @include border-radius(0);  }    .panel-default {      .panel-heading {          background-color: $color-grey;      }  }    .panel-group {      .panel-2 {          background: transparent;            .panel-heading {              padding: 18px 0px 18px 45px;              border-bottom: 1px solid $color-line-dark;                .panel-title {                  position: relative;                  font-size: 20px;                    > a {                      &:before {                          position: absolute;                          top: 0;                          left: -40px;                          width: 24px;                          height: 24px;                          content: ' ';                          @include border-radius(50%);                          background: $color-grey-3;                          color: #fff;                          font-family:'FontAwesome';                          font-size: 14px;                          text-align: center;                          padding: 5px;                          content:"\f068";                      }                      &[aria-expanded="false"]:before {                          content: "\f067";                      }                  }                 }          }          .panel-body {              border-top: none !important;              padding: 18px 0px 18px 45px;          }            & + .panel-2 {              margin-top: 0;          }      }  }    html[dir="rtl"] {      .panel-group {          .panel-2 {              .panel-heading {                  padding: 18px 45px 18px 0;                  .panel-title {                      > a {                          &:before {                              right: -40px;                              left: auto;                          }                      }                     }              }              .panel-body {                  padding: 18px 45px 18px 0;              }          }      }  }  

my gemfile

source 'http://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.7'  # Use sqlite3 as the database for Active Record  group :development, :test do    gem 'sqlite3'  end    group :production do    gem 'pg'  end  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'    gem 'bootstrap-sass', '~> 3.2.0'  gem 'autoprefixer-rails'  gem 'compass'    # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

I have used this theme previously on my other rails project and it had worked fine.

Rails - LoadError (Expected xxx/controllers/application_controller.rb to define ApplicationController)

Posted: 12 Nov 2016 01:31 AM PST

I build a backend service (nginx + passenger + rails) on AWS. My service is running as expected most of the time but sometimes goes wrong when passenger creates a weird new process to handle request:

[INFO] Started POST "/apixxxxxx"  [FATAL] LoadError (Expected /xxxxxxxx/app/controllers/application_controller.rb to define ApplicationController):  [INFO] Started POST "/apixxxxxx"  [FATAL] ActionController::RoutingError (uninitialized constant ApplicationController):  [INFO] Started POST "/apioooooo"  [FATAL] ActionController::RoutingError (uninitialized constant ApplicationController):  ...  

It has some signature on this weird process:

  • Other ruby process still works fine when this specific weird ruby process keeps failing on every new request.
  • If error happens, it always starts by the "LoadError" in the beginning of the process's first request.
  • This kind of "uninitialized constant" error keeps forever as long as this process is alive.

Here is some information of my machine:

  • ec2 type : m4.large
  • storage : general purpose SSD (use EBS)
  • system : ubuntu 14.04.2 (not AWS version)
  • application : version 1.8.1, passenger 5.0.26, Rails 3.2.22.2, ruby 2.2.4p230, sidekiq 4.1.1

I also googled some keyword like "AWS EBS volume's IOPS limit" or "sidekiq thread" with this LoadError issue but no luck. Is there any new direction to investigate this problem?

How does devise's remember_user_token work?

Posted: 12 Nov 2016 01:10 AM PST

When I see rails log I see only 1 sql for authorized user, like:

 User Load (44.9ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1  [["LIMIT", 1]]  

And I could find in my browser cookie: remember_user_token with random string. But how rails understands that it's user with id=1?

Uploading videos on YouTube with Ruby on Rails

Posted: 12 Nov 2016 01:10 AM PST

I am relatively new to Ruby on Rails and I want to make all users upload videos on my YouTube account. To do so I have to use oauth to send my gmail and gmail password and to get the access token and pass it to the user who is currently logged in my website. Sadly, I don't know how to do that and any help will be appreciated.

How to create mail chimp list using gibbon gem in Rails?

Posted: 12 Nov 2016 03:22 AM PST

I have created a rails app with rails 3.2 and ruby 2.1.2. I have used gibbon gem for accessing mail chimp API for create/edit/delete mail chimp list and also to manage subscribers. I am unable to create new mail chimp list using methods provided by gibbon. But I am able to get already created(default lists in mail chimp web app) lists. I want to know how to create a mail chimp list. I did not find examples for the same in github page.

Rails Heroku SSL https:// redirect

Posted: 11 Nov 2016 10:49 PM PST

I have a Rails 5 app with Heroku's SSL added. www.example.com and example.com works fine but when I preface my site with "https://" It doesn't work, but "http://" works.

I'm using Namecheap.com for my DNS. How do I go about getting "https://example.com" to direct to my heroku app?

Utilize external script function in React?

Posted: 12 Nov 2016 12:48 AM PST

I'm trying to load the Twilio Video client-side script into my React + Rails project. In index.html I have these two external scripts from Twilio:

<script src="https://media.twiliocdn.com/sdk/js/conversations/v0.13/twilio-conversations.min.js"></script>  

I can't figure out for the life of me how to access Twilio from a React component so that I can begin to utilize this script in my app. Must be a no-brainer way, right?

rake aborted! ActionView::Template::Error: undefined method 'challenges' for nil:NilClass

Posted: 11 Nov 2016 11:00 PM PST

I run this rake:

task monthly_report: :environment do    User.all.each do |user|      if user.challenges.present? && user.challenges.any?        UserMailer.monthly_report(user).deliver_now        end    end  end  

Now maybe in the each method itself is there a way to not send to user's who don't have any challenges?

I keep getting this error:

ActionView::Template::Error: undefined method 'challenges' for nil:NilClassafter I run in productionheroku run rake monthly_report

A user has_many challenges and challenges belongs_to user.

user_mailer.rb

  def monthly_report(user)      @user = user if user.email.present?      mail to: user.email, subject: "Sorry! Please Ignore | Testing Email - Monthly Challenges Report"    end  

monthly_report.html.erb

Accomplished: <%= @user.challenges.accomplished.count %> Ongoing: <%= @user.challenges.unaccomplished.count %>        <% if @user.challenges.accomplished.present? %>          <% @user.challenges.accomplished.order("deadline ASC").each do |challenge| %>              <% if challenge.date_started != nil %>                  <%= link_to challenge_url(challenge) do %>                      <%= challenge.name %> <%= challenge.committed_description %> for <%= challenge.days_challenged %> Days          <% end %>&nbsp;&nbsp;          <% if challenge.deadline.present? %>              <span style="display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; background-color: #446CB3; text-decoration: none;"><%= challenge.deadline.strftime("%b %d, %Y") %></span>          <% end %>              <% else %>                  <%= link_to challenge_url(challenge) do %>                      <%= challenge.name %>                  <% end %>&nbsp;&nbsp;                  <% if challenge.deadline.present? %>                      <span style="display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; background-color: #446CB3; text-decoration: none;"><%= challenge.deadline.strftime("%b %d, %Y") %></span>                  <% end %>              <% end %>          <% end %>      <% else %>          None.             <% end %>  

Error - 11750 TwiML response body too large

Posted: 11 Nov 2016 10:11 PM PST

Hi i have integrated twilio in application. In twilio every thing is working fine for me. But once the call ended am getting Error - 11750 TwiML response body too large. Here what i have did from my end.

def connect   twiml1 = Twilio::TwiML::Response.new do |r|     r.Say "You have joined the conference."     r.Dial do |d|      d.Conference "#{conference_title} #{call.id}",       waitUrl: " ",       muted: "false",       startConferenceOnEnter: "true",       endConferenceOnExit: "true",       maxParticipants: 5      end     end    render xml: twiml1.to_xml  end  

Once the conference ended am doing some payment related to application requirement.

def call_status  if params["CallStatus"] == "completed"    request_call = RequestCall.find { |c| c.caller_sids.include?(params["CallSid"])}    if request_call.present?      #save call logs      call_log = CallLog.new(called: params[:Called], tostate: params[:CallerCountry], callercountry: params[:CallerCountry], callerzip: params[:CallerZip],        direction: params[:Direction], timestamp: params[:Timestamp], callbacksource: params[:CallbackSource], callerstate: params[:CallerState],        tozip: params[:ToZip], sequencenumber: params[:SequenceNumber], callsid: params[:CallSid], to: params[:To], calledzip: params[:CalledZip],        calledcity: params[:CalledCity], tocountry: params[:ToCountry], apiversion: params[:ApiVersion], callstatus: params[:CallStatus], duration: params[:Duration],        from: params[:From], callduration: params[:CallDuration], accountsid: params[:AccountSid], calledcountry: params[:CalledCountry], callercity: params[:CallerCity],        caller: params[:Caller], fromcountry: params[:FromCountry], tocity: params[:ToCity], fromcity: params[:FromCity], calledstate: params[:CalledState], fromzip: params[:FromZip],        fromstate: [:FromState], user_id: request_call.user_id, expert_id: request_call.expert_id, request_call_id: request_call.id)        call_log.save      #check caller length      if request_call.call_ended == false && request_call.call_id_length == true        # Check estimate time with total duration        if request_call.estimated_time.to_i == call_log.duration.to_i          release_payment = request_call.release_full_payment        elsif request_call.estimated_time.to_i < call_log.duration.to_i          make_payment = request_call.release_full_payment          express_item_id = request_call.express_item_id          extra_time = call_log.duration.to_i - request_call.estimated_time.to_i          pending_amount = request_call.price_to_pay(extra_time)          second_item = request_call.express_item(pending_amount)          if second_item.code == 200            express_payment = request_call.release_express_payment          end          render json: {status: true}        elsif request_call.estimated_time.to_i > call_log.duration.to_i          remaining_duration = request_call.estimated_time.to_i - call_log.duration.to_i          refund_amount = request_call.price_to_pay(remaining_duration)          refund = request_call.refund_partial_amount(refund_amount)          release_fund = request_call.release_full_payment          render json: {status: true}        end        request_call.transition_to!(:completed)        request_call.update(twilio_allocated_number: nil, twilio_access_code: nil, call_ended: true)      elsif request_call.call_ended == true && request_call.call_id_length == true        render json: {status: true}      elsif request_call.call_ended == false && request_call.call_id_length == false        #make payment        request_call.transition_to!(:completed)        request_call.update(twilio_allocated_number: nil, twilio_access_code: nil, call_ended: true, single_user: true)        render json: {status: true}      end    else      render json: {status: false}    end  else    render json: {status: false}  end  

end

I don't know what i have did wrong in this. Please advice me.

Rails has_many index column can't be null

Posted: 11 Nov 2016 10:34 PM PST

I am making a Message model, the association is

User has_many messages  Message belongs_to user  

There are two kind of messages, one is public and the other is private. It depends on its is_public column.

Here is my message schema

create_table "messages", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|    t.string   "title"    t.text     "content",    limit: 65535    t.boolean  "is_public"    t.integer  "user_id"    t.datetime "created_at",               null: false    t.datetime "updated_at",               null: false    t.index ["user_id"], name: "index_messages_on_user_id", using: :btree  end  

I think only private message should contain user_id.

However, I found out that I can't create message directly.

For example

m = Message.create  => #<Message:0x007fa6724e9d80 id: nil, title: nil, content: nil, is_public: nil, user_id: nil, created_at: nil, updated_at: nil>  Message.count   => 0  User.first.messages << m  Message.count  => 1  

Is there a better way I can keep the index and create message without associating?

JQuery can't find the Sub Category ID

Posted: 11 Nov 2016 10:57 PM PST

I followed the instructions in this question's answer by emmanuel and the form now finds the Category ID and submits it but does not find the Sub Category ID associated with the Category and does not save it.

The params are taken which can be noted by this, Parameters: {"utf8"=>"✓", "authenticity_token"=>"PTRTGGblf3HoWNXmanKl8TIP7F4j/QKTLN2Wd6oKSQWSXV27qioztUpXgb6YjHEroaWf8dgTzUIgQiRBK2XxWQ==", "post"=>{"title"=>"200k", "description"=>"FMxd123", "category_id"=>"2", "subcategory_id"=>"9"}, "commit"=>"Create Post"}

It then shows the error message on my screen (with my error partial) that "Sub Category must exist. The SQL output is like so:

  (0.2ms)  begin transaction   Category Load (0.1ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]       (0.0ms)  rollback transaction    Rendering posts/new.html.erb within layouts/application    Rendered shared/_errors.html.erb (0.8ms)    Category Load (0.1ms)  SELECT "categories".* FROM "categories"    CACHE (0.0ms)  SELECT "categories".* FROM "categories"      SubCategory Load (0.1ms)  SELECT "sub_categories".* FROM "sub_categories" WHERE "sub_categories"."category_id" = ?  [["category_id", 1]]    SubCategory Load (0.1ms)  SELECT "sub_categories".* FROM "sub_categories" WHERE "sub_categories"."category_id" = ?  [["category_id", 2]]    SubCategory Load (0.1ms)  SELECT "sub_categories".* FROM "sub_categories" WHERE "sub_categories"."category_id" = ?  [["category_id", 3]]  

My Posts.coffee:

jQuery ->    subcat = $('#subcategory-select').html()    $('#category-select').change ->      cat = jQuery('#category-select').children('option').filter(':selected').text()      options = $(subcat).filter("optgroup[label='#{cat}']").html()      if options        $('#subcategory-select').html(options)      else        $('#subcategory-select').empty()

And the part where category_id and sub_category_id are taken in the form with select boxes:

  <p>  	<%= f.label :category_id%>  	<%= f.collection_select(:category_id, Category.all, :id, :name,      	               { prompt: 'Select a category' }, { id: 'category-select' }) %>    </p>    <p>  	<%= f.label :subcategory_id%>  	<%= f.grouped_collection_select :subcategory_id, Category.all, :sub_categories,             :name, :id, :name, { include_blank: 'Select a sub category' },                                                 { id: 'subcategory-select' } %>     </p>

Confused as to how it isn't working because it made my category_id get saved when it wasn't working. Any ideas?

rails 5 devise - undefined method 'api' for Api::V1::SessionsController:Class

Posted: 11 Nov 2016 07:17 PM PST

Working with rails 5 trying to create a simple api to register users.

Controller:

class Api::V1::SessionsController < Devise::SessionsController    protect_from_forgery    respond_to :json    skip_before_action :verify_authenticity_token #, only: [:create]        api :POST, "/v1/create_account", "Create User Account"      param :user, Hash do      param :email, :undef      param :password, :undef    end      def create_account      user = params[:user]        existing_user = User.find_by_email user[:email].strip        return email_already_taken if !existing_user.nil?        user = User.create(:email => user[:email],                          :password => user[:password],                          :password_confirmation => user[:password])    end    end  

Routes:

Rails.application.routes.draw do    devise_for :admin_users      namespace :api, defaults: {format: "json"} do      namespace :v1 do      devise_for :users, :controllers => {:sessions => "api/v1/sessions"}, :path_prefix => 'api/v1'          devise_scope :user do          post :create_account, to: "sessions#create_account"        end    end  end  end  

Trace:

The trace is talking about the api: POST piece of the controller but why is it giving this error??

ActionController::RoutingError (undefined method `api' for Api::V1::SessionsController:Class):    app/controllers/api/v1/sessions_controller.rb:6:in `<class:SessionsController>'  app/controllers/api/v1/sessions_controller.rb:1:in `<top (required)>'    Rendering /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout    Rendering /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.8ms)    Rendered collection of /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [31 times] (10.4ms)    Rendered /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_table.html.erb (6.7ms)    Rendering /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (9.7ms)    Rendered /Users/local/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout (112.5ms)  source=rack-timeout id=43f3c961f7e1e94e4ffe0a55b167d831 timeout=15000ms service=415ms state=completed  

How can I solve this problem?

How to fix drop table migration rollback with empty down method

Posted: 11 Nov 2016 10:45 PM PST

I made a mistake at work by running rake db:migratewith bunch of migrations. I ran rake db:rollback to roll those back to previous state. One of the migrations had drop table in the "up" method. The same migration's "down" method was empty. Now rails keeps complaining that this table does not exist in mysql, and it will not start. I see in schema.rb this table is not present anymore. Just to be thorough we have two app servers, and 2 rails admin servers running this code. This issue is happening on rails_admin servers only.
Is there a way to fix this error.

EDIT: These tables are not needed anymore, so don't care about the data. I just want to be able to start my app without seeing the error "mysql2::error: table "xyz" doesn't exit

Why does my content_tag not produce the HTML I expect?

Posted: 11 Nov 2016 06:57 PM PST

I am rendering my Profiles#Index view. In that view, I call this helper method:

<%= ratings_labels(profile, params[:rating]) %>  

That is defined in profiles_helper.rb, like so:

def ratings_labels(profile, rating_param)      rating_classes = {        'speed'     => 'label label-success label-lg',        'tackling'  => 'label label-info label-lg',        'passing'   => 'label label-warning label-lg',        'dribbling' => 'label label-primary label-lg'      }        rating_classes.each do |rating, klass|            content_tag :div, class: "col-lg-3" do          content_tag :span, class: "#{klass}" do            "#{rating.capitalize}: #{profile.ratings.find_by(user: current_user)[rating]}"          end        end      end         end    end  

However, what the outputs in my HTML is this:

{"speed"=&gt;"label label-success label-lg", "tackling"=&gt;"label label-info label-lg", "passing"=&gt;"label label-warning label-lg", "dribbling"=&gt;"label label-primary label-lg"}  

Notice there is no HTML generated. No div.col-lg-3 or span.

Why is that?

No comments:

Post a Comment