Sunday, January 22, 2017

rails: render partial with jquery foreach | Fixed issues

rails: render partial with jquery foreach | Fixed issues


rails: render partial with jquery foreach

Posted: 22 Jan 2017 07:34 AM PST

i would like to append in my view several times a partial with different params. i have a search form that return a projects json with ajax. now i would like to call get jquery fonction with a project and show it in the view.

$.ajax({            type:"GET",            url:"mycontroller/projects",            //dataType:"json",            data: {project: project, user: user,periode: periode },            success:function(result){              if(result.length == 0 ){                  $("#notice").show().fadeOut(5000)              }else{                    $.each(result, function(i, item) {                      $("#res").append(**mypartial**)                  });              }                  }          })

and the in my partial a will do something like:

  Poject : %= preject.name %  users:  % project.users.each do |user| %  - %= user.name %  %end%  

there's a way to do this please ?

Searching for files with a specific pattern

Posted: 22 Jan 2017 07:50 AM PST

I'm trying to look for specific files in a directory using a pattern

Lets say i have the id of the user - 101

here are my files

101  101_2  101_5  10111  103  10125  101_6  

I'm trying to form a regex pattern which only gives me files (101,101_2,101_5,101_6)

I'm trying the below pattern

^101_?\d+$  

but it doesnt seem to pick any of the files at all. if i remove the ^.only 101_6 matches for some reason.

EDIT:

I'm using rails/ruby to look for files in the particular directory. so something like

Dir.glob(location).grep("^101_?\d+$")   do something  end  

Using firebase messaging in a Rails App

Posted: 22 Jan 2017 06:17 AM PST

I want to recieve notifications in my rails app and show them to the user (which accept to get notification)

I setup the client with

firebase.initializeApp(config);  const messaging = firebase.messaging();  

Then

messaging.requestPermission().then(..)  

I added "public/firebase-messaging-sw.js" and "public/manifest.json"

I can't get the message using "onMessage" but I want to get them in background

enter image description here

How to show the gravatar of the user who is following in Rails

Posted: 22 Jan 2017 06:57 AM PST

All, i am currently learning Rails and proceeding with a project and i am running into an issue.I am unable to show the image of the user who the post belongs to.

When i go to the home page, i should see the post of the users who you are following ... and unfortunately i am not sure how i can show the image of user who the post belongs to.... i can show their post but not sure how i show their image. I must say i am using paperclip gem.

user model

class User < ActiveRecord::Base  

# Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }, :default_url => "/images/:style/missing.png" validates_attachment_content_type :avatar, :content_type => /\Aimage/.*\Z/

     has_many :followeds, through: :relationships        has_many :relationships, foreign_key: "follower_id", dependent: :destroy       has_many :followed_users, through: :relationships, source: :followed       has_many :reverse_relationships, foreign_key: "followed_id"       has_many :reverse_relationships, foreign_key: "followed_id",                                 class_name:  "Relationship",                                 dependent:   :destroy       has_many :followers, through: :reverse_relationships, source: :follower           has_many:avatar, dependent: :destroy       has_many :posts, dependent: :destroy # remove a user's posts if his account is deleted.       has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy       has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy         has_many :following, through: :active_relationships, source: :followed       has_many :followers, through: :passive_relationships, source: :follower              def avatar_url      avatar.url(:medium)      end         # helper methods         # follow another user       def follow(other)         active_relationships.create(followed_id: other.id)       end         # unfollow a user       def unfollow(other)         active_relationships.find_by(followed_id: other.id).destroy       end         # is following a user?       def following?(other)         following.include?(other)         end       end  

i can get the current user image, but if i log into my account, and i am following someone, i want to see their image not mine for their associated post..

             <%=image_tag(current_user.avatar.url, class: "img-circle img-responsive img-raised", :size => "100x100") %>  

Ruby SSL Error when trying to crawl website

Posted: 22 Jan 2017 06:05 AM PST

So, basically im trying to run this script https://github.com/JeffreyATW/mbfc_crawler and it gives me this error:

C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)      from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:933:in `connect'      from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:863:in `do_start'      from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:858:in `start'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:700:in `start'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:631:in `connection_for'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:994:in `request'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/mechanize-2.7.5/lib/mechanize/http/agent.rb:274:in `fetch'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/mechanize-2.7.5/lib/mechanize.rb:464:in `get'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/wombat-2.5.1/lib/wombat/processing/parser.rb:61:in `public_send'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/wombat-2.5.1/lib/wombat/processing/parser.rb:61:in `parser_for'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/wombat-2.5.1/lib/wombat/processing/parser.rb:44:in `parse'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/wombat-2.5.1/lib/wombat/crawler.rb:30:in `crawl'      from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/wombat-2.5.1/lib/wombat.rb:13:in `crawl'      from crawler.rb:21:in `block in <main>'      from crawler.rb:20:in `each'  

I have installed Ruby 2.3.3 from Ruby Installer for Windows.

I have also installed the DevKit-mingw64-64-4.7.2-20130224-1432-sfx.exe for my machine(from the same site).

What am i doing wrong? Thanks for your time.

Array of hashes is overriding data directly to array

Posted: 22 Jan 2017 06:20 AM PST

I want to make an array of hashes. But the problem is after first iteration when code goes to next line then it directly replaces the content of array.

@item_name =[]  item = {}  @invoiceinfo.each do |invoice|    item[:name] =  Invoiceinfo.find(@invoiceinfo.id).item.name    item[:desc] =  Invoiceinfo.find(@invoiceinfo.id).desc    item[:unit_price] =  Invoiceinfo.find(@invoiceinfo.id).unit_price    byebug    @item_name.push (item)  end  

This is what i am getting after first iteration suppose i have this data

@item_name = [{:name=>"usman", :desc=>"sample ", :unit_price=>100}]  

As soon as next line is executed it directly changes @item_name(name variable) After executing item[:name] = Invoiceinfo.find(@invoiceinfo.id).item.name the content of the @item_name is changed

@item_name = [{:name=>"next_name", :desc=>"sample ", :unit_price=>100}]

Any help would be appreciated. Thannks

Rails N+1 when referencing to the same model twice

Posted: 22 Jan 2017 05:43 AM PST

I have 2 models:

class User < ActiveRecord::Base    end    class Message < ActiveRecord::Base    has_one :sender, :class_name => 'User'    has_one :recipient, :class_name => 'User'  end  

and I want to get all the messages that a user recieved so in messages_controller.rb i have:

  def messages_to_user      messages = Message.where(recipient_id: current_user.id)        respond_with messages    end  

this service works but in the log I can see classic N+1 issue:

Started GET "/messages_to_user" for 127.0.0.1 at 2017-01-22 15:35:01 +0200  Processing by MessageController#user as */*    User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]    Message Load (0.0ms)  SELECT "messages".* FROM "messages" WHERE "messages"."recipient_id" = ?  [["recipient_id", 2]]  [active_model_serializers]   User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers]   CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]  [active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (42.01ms)  Completed 200 OK in 217ms (Views: 63.0ms | ActiveRecord: 3.0ms)  

So I tried to solved it by adding includes:

  def messages_to_user      messages = Message.includes(:recipient).where(recipient_id: current_user.id)        respond_with messages    end  

But then I get the following error:

SQLite3::SQLException: no such column: users.message_id: SELECT "users".* FROM "users" WHERE "users"."message_id" IN ('1', '2', '3', '4', '5', '6', '7', '8', '9')  

How it can be fixed? I want to return a collection of messages - not a user and a messages set inside the user. but without the N+1 problem

Rspec prevent method from being called

Posted: 22 Jan 2017 07:00 AM PST

I am testing a controller method for creating new orders (e-commerce-like app). If user is present in the system, he should be redirected to new_user_session_path, else to new_order_path. Simple as that.

This is my orders_controller.rb

def new          if !User.where(phone: params[:phone]).blank? && !user_signed_in?                redirect_to new_user_session_path()              flash[:info] = "Already present"          else              @order = Order.new              @menu = Menu.find(params[:menu_id])              @menu_price = @menu.calculate_price(@menu, params)          end      end  

In my app, I need the calculate_price method to be called, because it calculates the overall price given the params. But in my test, I just want to ensure, that the redirect is correct.

Right now I'm getting errors like (they are sourced inside the Menu.rb file, since calculate_price is called) :

Front::OrdersController#new redirects user to new order page if user is not present in the system       Failure/Error: menu_price_change = menu_amount.split(",")[1].gsub(" ","").gsub("]",'')         NoMethodError:         undefined method `split' for nil:NilClass  

This is my spec file:

require 'rails_helper'      describe Front::OrdersController, type: :controller do      describe '#new' do          # Set up dummy menu          let (:menu) { Menu.create() }            it "redirects user to sign up page if user is present in the system" do              user = User.create(name: "Bob", password: "bobspassword", phone: "+7 (903) 227-8874")                get :new, params: { phone: user.phone }              expect(response).to redirect_to(new_user_session_path(phone: user.phone))          end            it "redirects user to new order page if user is not present in the system" do              non_present_phone = "+7 (903) 227-8874"                  get :new, params: { phone: non_present_phone, menu_id: menu.id}              expect(response).to redirect_to(new_order_path)          end        end  end  

Of course I could provide all the params, but there is a pretty big amount of them and besides, I just want to test the correct redirect. As far as I know, mocks and subs are useful in this case, when you want to explicitly test the methods. But in my case, I want to - somehow - omit them. How can I ensure that behaviour?

Unable to install will_paginate gem

Posted: 22 Jan 2017 05:34 AM PST

I tried installing will_paginate gem in rails but it somehow not working in mine. I am unable to start my rails server.

Bundler::GemNotFound: Your bundle is locked to will_paginate (3.1.5), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of will_paginate (3.1.5) has removed it. You'll need to update your bundle to a different version of will_paginate (3.1.5) that hasn't been removed in order to install.

Soundcloud embed player in rails

Posted: 22 Jan 2017 04:18 AM PST

I am a beginner and trying to work out how to use rails..I am making a CRUD system to play soundcloud tracks on my website. I'm creating a form so I can 'create' a song by inserting the soundcloud embed code in the fieldset to display the soundcloud widget on the view page. My question is how can I use the embed code in the form below??

<%= form_for @song do |f| %>  <fieldset>    <%= f.label :name %>    <%= f.text_field :name %>  </fieldset>    <fieldset>    <%= f.label :artist_id %>    <%= f.select :artist_id, Artist.pluck(:name, :id), :include_blank => true %>  </fieldset>    <fieldset>    <label></label>    <%= f.submit %>  </fieldset>    <% end %>  

this is my Songs controller

class SongsController < ApplicationController    def index      @songs = Song.all    end      def new      @song = Song.new    end      def create      song = Song.create song_params      redirect_to song    end      def edit      @song = Song.find params[:id]    end      def update      song = Song.find params[:id]      song.update song_params      redirect_to song      end      def show      @song = Song.find params[:id]    end      def destroy      song = Song.find params[:id]      song.destroy      redirect_to artists_path    end      private    def song_params      params.require(:song).permit(:name, :artist_id, :user_id)    end      end  

Also I can't use the soundcloud API because I applied for it but I didn't receive a response. Would there be a way to display the widget on the website without the api? Can anybody let me know if this is the right approach and a step by step guide on how I can achieve this?

Thank you so much..

Rendering a form after Ajax request doesn't load tinyMCE 4 plugin (again)

Posted: 22 Jan 2017 04:03 AM PST

I have a form partial being loaded in my view 'powered' with tinyMCE. I'd like the form to do the following:

  1. Create an instance of OpenEnder via Ajax
  2. After creation a form should still be there, loading the recently saved @open_ender allowing the instance to be updated via Ajax again
  3. TinyMCE should be always available for text formatting.

I'm able to achieve the first 2 points. However, although tinyMCE is loaded when the page is first rendered, I haven't been successful keeping tinyMCE active after the Create Ajax action.

The issue is driven by the need of re-rendering the form partial after a Create Action in order to update the HTTP method so it updates the instance rather than keep creating instances. When I do this tinyMCE is not loaded in the new form.

I've tried re-loading tinymce init after Create, wrapping tinymce.init in a function so I can call it after Create tinymce.remove() before calling init function as suggested in here without success. Any help would be appreciated.

layouts/application.html.erb (in )

<script>  var initTinymce = function() {    tinymce.init({      selector: ".tinymce",      plugins: [        "autosave save"],      toolbar1: "save restoredraft | fullscreen | undo redo ",      autosave_retention: "20m"    });   }     initTinymce();  <script>  

answers/show.html.erb

      <%= render 'open_enders/form', open_ender: @open_ender, answer: @answer %>  

open_enders/_form.html.erb

<%= simple_form_for open_ender, remote: true, authenticity_token: true, html: { id:'open_ender_form' } do |f| %>  <%= f.error_notification %>      <div class="form-inputs">          <%= f.input :answer_id, :required => true, :as => :hidden, :autofocus => true, input_html: {value: @answer.id } %>          <%= f.input :content, :label => false, :placeholder => "write your thoughts here...", :required => true, :autofocus => true, input_html: {  class:'tinymce' } %>          <%= button_tag(type: 'submit', id: "save-btn", style:'background:transparent' ) do %>              <span id="inline_alert" class="hide">Remember to save your changes!</span>          <% end %>      </div>  <% end %>  

open_enders/create.js.erb

('#open_ender_form').replaceWith("<%= j render 'open_enders/form', open_ender: @open_ender, answer: @answer %>");  initTinymce();  

open_enders_controller.rb

  def create      @open_ender = OpenEnder.new(open_ender_params)      respond_to do |format|          if @open_ender.save            format.js          else            #code when not saved        end      end      @answer = @open_ender.answer    end      def update      respond_to do |format|        if @open_ender.update(open_ender_params)          format.js         else          #code when not updated        end      end    end  

Rails on WINDOWS: install therubyracer & libv8 - working on a website designed on MAC

Posted: 22 Jan 2017 03:37 AM PST

I have a website developed with was RoR v 4.2.4 on MAC which needs some adaptions and I'm trying to get in running on my windows 10 (because I don't have a MAC).I was not successfull with the rails installer and rails 5.0.

After a lot of pain installing RoR 4.2.4 with ruby 2.2.6 I managed to install nearly all missing gems using bundle check, bundle install and gem install xyz -v 0.0.... But now I'm really stuck with the last 2: therubyracer and libv8

What I tried:

Install libv8 with gem install libv8 -v 3.16.14.11 -- --with-system-v8 and also the therubyracer-for-windows which is mentioned here.

Modify the gemfile.lock to get rid of the dependencies like:

group :production do    gem 'therubyracer'  end  

and tried bundle install --without production. But then I get an error when starting the server.

At the moment bundle check says that therubyracer v 0.12.2 is the last missing gem. libv8 is installed with --with-system-v8. gem list says libv8 (3.16.14.11) and therubyracer (0.11.0b) is installed but the systems does not seems to find therubyracer because: therubyracer -v does not work. Furthermore bundle install give me the follwing error:

C:/Ruby22-x64/bin/ruby.exe -r ./siteconf20170122-10664-jwvn48.rb extconf.rb  --with-v8-dir=/usr/local/opt/v8-315  checking for main() in -lpthread... yes  checking for v8.h... no  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:          --with-opt-dir          --without-opt-dir          --with-opt-include          --without-opt-include=${opt-dir}/include          --with-opt-lib          --without-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=C:/Ruby22-x64/bin/$(RUBY_BASE_NAME)          --with-pthreadlib          --without-pthreadlib          --enable-debug          --disable-debug          --with-v8-dir          --with-v8-include          --without-v8-include=${v8-dir}/include          --with-v8-lib          --without-v8-lib=${v8-dir}/lib  C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/libv8-3.16.14.11/ext/libv8/location.rb:50:in  `configure': You have chosen to use the version of V8 found on your system  (Libv8::Location::System::NotFoundError)  and *not* the one that is bundle with the libv8 rubygem. However,  it could not be located. please make sure you have a version of  v8 that is compatible with 3.16.14.11 installed. You may  need to special --with-v8-dir options if it is in a non-standard  location    thanks,  The Mgmt    from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/libv8-3.16.14.11/lib/libv8.rb:7:in  `configure_makefile'          from extconf.rb:32:in `<main>'    extconf failed, exit code 1    Gem files will remain installed in  C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/therubyracer-0.12.2 for inspection.  Results logged to  C:/Ruby22-x64/lib/ruby/gems/2.2.0/extensions/x64-mingw32/2.2.0/therubyracer-0.12.2/gem_make.out    An error occurred while installing therubyracer (0.12.2), and Bundler cannot  continue.  Make sure that `gem install therubyracer -v '0.12.2'` succeeds before bundling.  

This error is at least similar to all the ones I get before, when trying to install therubyracer after I installed libv8 with --with-system-v8.

Sorry if this information is a bit chaotic, but I tried so many things over about a day now and was not always 100% sure what I doing :)...quite hard to summarizes as much as possible. If there is important information missing, let me know.

By the way: I followed this guide as good as possible. Creating/Developping a new website with rails new blog and running the server for it works perfectly...the problem is only with the existing website I have to complete.

Can someone help me? Is there any way to get the website running on my windows pc? Thanks!

filterrific-jquery.self-2b08b3c….js?body=1:93 Uncaught TypeError: $(...).filterrific_observe_field is not a function

Posted: 22 Jan 2017 03:34 AM PST

Hey just recently i have been getting this error and i'm not to sure how to fix it everything was working well before. It makes the layout of the page funny why is that?

Here are my code and files any help will be appreciated.

index.js.erb

<% js = escape_javascript(    render(partial: 'invoices/list', locals: { invoices: @invoices })  ) %>  $("#filterrific_results").html("<%= js %>");  

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require filterrific/filterrific-jquery  //= require turbolinks  //= require bootstrap  //= require_tree .  

index.html.erb

<%= form_for_filterrific @filterrific do |f| %>        <div>      Hotel      <%= f.select(              :with_hotel_id,        @filterrific.select_options[:with_hotel_id],        { include_blank: '- Any -' }      ) %>    </div>      <div>      Staff ID      <%= f.select(              :with_user_id,        @filterrific.select_options[:with_user_id],        { include_blank: '- Any -' }      ) %>    </div>      <div>      Check In      <%#= f.text_field(:with_created_at_gte, class: 'js-datepicker') %>      <%= f.date_field(:with_created_at_gte)  %>    </div>    <div>      Before      <%#= f.text_field(:with_created_at_gte, class: 'js-datepicker') %>      <%= f.date_field(:with_created_at_lte)  %>    </div>      <div>      <%= link_to(        'Reset filters',        reset_filterrific_url,      ) %>    </div>    <%# add an automated spinner to your form when the list is refreshed %>    <%= render_filterrific_spinner %>  <% end %>    <%= render(    partial: 'invoices/list',    locals: { invoices: @invoices }  ) %>        <% if false %>          <tr>              <font size="6">No. of rooms: <%= @rooms %></font><br>              <font size="6">Total (RM): <%= @money %></font><br>                <div id="spoiler" style="display:none">                  <table class="table">                      <tr>                          <th><b>Guest name</b></th>                          <th><b>IC/Passport</b></th>                          <th><b>Room number</b></th>                          <th><b>Total (RM)</b></th>                      </tr>                  <% @invoices.each do |inv| %>                      <tr class="<%= inv.special %> data-item" data-id ="<%= inv.hotel_id %>">                          <td><%= link_to inv.name, invoice_path(inv) %></td>                          <td><%= inv.identification %></td>                          <td><%= inv.room %></td>                          <td><%= inv.rate * inv.days %></td>                          <td class="col-md-1"><%= link_to "Edit", edit_invoice_path(inv)%></td>                          <% if current_user.sk?%>                          <td class="col-md-1"><%= link_to "Delete", inv, method: :delete, data: {confirm: 'Are you sure you want to delete this invoice?'} %></td>                  <% end %>                      </tr>                      <% end %>                  </table>              </div>  <% end %>  

invoice.rb

class Invoice < ActiveRecord::Base    validates :name, presence: true    validates :identification, presence: true    validates :dob, presence: true    validates :room, presence: true    validates :days, presence: true    validates :rate, presence: true        filterrific(      default_filter_params: { sorted_by: 'created_at_desc' },      available_filters: [        :sorted_by,        :with_hotel_id,        :with_user_id,        :with_created_at_gte,        :with_created_at_lte,      ]    )        belongs_to :hotel    belongs_to :user  #  # scope :search_query, lambda { |query|  #     # Filters students whose name or email matches the query  #  #   }    scope :sorted_by, lambda { |sort_key|      # Sorts students by sort_key      }    scope :with_hotel_id, lambda { |hotel_id|      # Filters students with any of the given hotel_ids      where(hotel_id: hotel_id)    }      scope :with_user_id, lambda { |user_id|      # Filters students with any of the given country_ids      where(user_id: user_id)    }    scope :with_created_at_gte, lambda { |ref_date|      where("created_at > ?", ref_date)    }      scope :with_created_at_lte, lambda { |ref_date|      where("created_at < ?", ref_date)    }      # This method provides select options for the `sorted_by` filter select input.    # It is called in the controller as part of `initialize_filterrific`.    def self.options_for_sorted_by      [        ['Name (a-z)', 'name_asc'],        ['Registration date (newest first)', 'created_at_desc'],        ['Registration date (oldest first)', 'created_at_asc'],      ]    end      scope :check_out, -> do      Invoice.where("julianday(created_at + days) = julianday(?)", Date.today)    end  end  

Azure: Rails and PostgreSQL on the same VM?

Posted: 22 Jan 2017 02:43 AM PST

I'm trying to combine a Rails app and PostgreSQL on the same Azure virtual machine. I installed PostgreSQL 9.5 following this guide and it seems to give no problems by itself. Now the problem is, I cannot install the pg gem. Specifically, running the command gem install pg -v '0.19.0', it gives me the following error:

Building native extensions.  This could take a while...  ERROR:  Error installing pg:          ERROR: Failed to build gem native extension.    current directory: /var/lib/gems/2.3.0/gems/pg-0.19.0/ext  /usr/bin/ruby2.3 -r ./siteconf20170122-18144-1ee3id1.rb extconf.rb  checking for pg_config... yes  Using config values from /usr/bin/pg_config  You need to install postgresql-server-dev-X.Y for building a server-side     extension or libpq-dev for building a client-side application.  You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.  checking for libpq-fe.h... no  Can't find the 'libpq-fe.h header  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may   need configuration options.    Provided configuration options:          --with-opt-dir          --without-opt-dir          --with-opt-include          --without-opt-include=${opt-dir}/include          --with-opt-lib          --without-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=/usr/bin/$(RUBY_BASE_NAME)2.3          --with-pg          --without-pg          --enable-windows-cross          --disable-windows-cross          --with-pg-config          --without-pg-config          --with-pg_config          --without-pg_config          --with-pg-dir          --without-pg-dir          --with-pg-include          --without-pg-include=${pg-dir}/include          --with-pg-lib          --without-pg-lib=${pg-dir}/lib    To see why this extension failed to compile, please check the mkmf.log which      can be found here:      /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/pg-0.19.0/mkmf.log    extconf failed, exit code 1    Gem files will remain installed in /var/lib/gems/2.3.0/gems/pg-0.19.0 for inspection.  Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/pg-0.19.0/gem_make.out  

Any help is really appreciated. Cheers

Rails AplicationController trouble

Posted: 22 Jan 2017 03:27 AM PST

I have it in my ApplicationController

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception    $banner = Banner.first    $template = Template.first  end  

and in my _myfile.html.erb

<%= $template.mainpage_benefits.html_safe %>  

My terminal has next error:

ActionView::Template::Error (undefined method `html_safe' for nil:NilClass  

I don't met this practice before($template = Template.first). Please, explain me, how i can fix it

carrierwave undefined method `url' for nil:NilClass

Posted: 22 Jan 2017 01:29 AM PST

I have the following error implementing carrierwave in order to upload images

gem 'carrierwave', '~> 1.0' Rails 5.0.1 ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

My model:

class Company < ApplicationRecord      mount_uploader :cover, CompanyAvatarUploader    attr_accessor :cover  

My CompanyAvatarUploader

   class CompanyAvatarUploader < CarrierWave::Uploader::Base        storage :file      def store_dir         "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"      end         def extension_whitelist       %w(jpg jpeg gif png)     end     end  

My company_controller.erb

class CompanyController < ApplicationController       def create           @company = Company.new(company_params)           respond_to do |format|             if @company.save             format.html { redirect_to @company, notice: 'Company saved...'}             format.json { render :show, status: :created, location: @company}           else             format.html { render new}             format.json { render json: @company.errors, status: :unprocessable_entity }             end  private    def company_params      params.require(:company).permit(:name, :address, :country, :telephone, :cover)    end    end  

My new.html.erb

<p>    <%= f.label :country %><br>    <%= f.text_area :country %>  </p>      <p>    <%= f.label :cover %><br>    <%= f.file_field :cover %>  </p>  

My show.html.erb

<p>    <strong>Country:</strong>    <%= @company.country %>  </p>  <p>    <%=    image_tag @company.cover.url  %>  </p>  

When I am trying to add a new company with the cover I have the following error:

NoMethodError in Company#show  Showing     app/views/company/show.html.erb where line #22 raised:    undefined method `url' for nil:NilClass  Extracted source (around line #22):      </p>  <p>    <%=    image_tag @company.cover.url %>  </p>  

The company information is storaged in my MySQL but not the cover

Thank you for your help

What's the difference of `require 'rails'` and `require 'rails/all'`?

Posted: 22 Jan 2017 12:47 AM PST

I know that generally when we require a gem, the gem's lib path will be added to $LOAD_PATH. But I didn't find a lib path in my rails gem. When I execute require 'rails' and require 'rails/all' in my console, they get different output.

ENOTFOUND: getaddrinfo ENOTFOUND api.heroku.com api.heroku.com:443 Error for heroku create

Posted: 22 Jan 2017 12:44 AM PST

My steps are below:

  1. Download the heroku-osx.pkg, and installed it.
  2. $ heroku login with my account and password
  3. cloned the ruby-getting-started: $ git clone https://github.com/heroku/ruby-getting-started.git
  4. But when I run $ heroku create in my Terminal.

Reports the error:

Creating app... !
▸ ENOTFOUND: getaddrinfo ENOTFOUND api.heroku.com api.heroku.com:443

I have find the related question in SO:

But they are not when execute $ heroku create comes out the error.

Rails predictor array_to_json [duplicate]

Posted: 22 Jan 2017 12:10 AM PST

This question already has an answer here:

I'm, trying to create a prediction of product using predictor gem and ip_address but rails spits out

no such function: array_agg

someone have any idea what this array_agg mean? thank's

gem link https://github.com/Pathgather/predictor

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such function: array_agg: SELECT ip_address, array_to_json(array_agg(product_id)) as product_ids FROM impressions GROUP BY ip_address

 impressions_data = Impression.connection.execute('SELECT ip_address, array_to_json(array_agg(product_id)) as product_ids FROM impressions GROUP BY ip_address')      impressions_data.each { |row| recommender.impressions.add_to_set(row['ip_address'], eval(row['product_ids'])) }  

Is there any books present on Neo4j and Ruby on Rails? [on hold]

Posted: 21 Jan 2017 10:30 PM PST

I wanted to start working on Neo4j with Rails. I am not able to get a proper guide, sample app or integration document. Is there any books available on this topic?

Any help will be appreciated

Thanks

How would i get all items in a list that have the same class?

Posted: 21 Jan 2017 10:03 PM PST

How would I get all the items with the class 'ingredient' and use it to create a new Ingredient? Im using nokogiri to grab the class. Im doing it like this but can only create one ingredient/ get the first item in the list.

require 'nokogiri'  require 'open-uri'    url = "http://damndelicious.net/2017/01/16/turkey-and-spinach-veggie-lasagna/"  doc = Nokogiri::HTML(open(url))      ingredients = Ingredient.create do |ingredient|    ingredient.name = doc.at_css(".ingredient").text  end  

This is an example of the list I am trying to get items from.

<li class="ingredient">1 tablespoon olive oil</li>  <li class="ingredient">2 cloves garlic, minced</li>  <li class="ingredient">1 onion, diced</li>  <li class="ingredient">2 zucchinis, diced</li>  

thanks

Unable to make auto focus on fields for bootstrap modal

Posted: 21 Jan 2017 11:32 PM PST

Hi so following this rails tutorial using coffeescript , a part of this function is suppose to find the bootstrap div modal, then find the "textarea" within it to auto focus it immediately .

ready = ->      $(".media").on "click", ->           document.location = $(this).data("target")          return false        $(".modal").on "shown.bs.modal", ->          $(this).find("textarea").focus()    $(document).ready(ready)  $(document).on "page:load", ready  

The .media function click is working so far. However, another function which uses the shown.bs.modal is not working... I tried to Console.log or alert it as well but it seems that $(".modal").on "shown.bs.modal", is not working and i'm not sure why.

Here is my html

<div class="modal fade" tabindex="-1" role="dialog" id='new-question-modal'>    <div class="modal-dialog" role="document">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>          <h4 class="modal-title">Modal title</h4>        </div>        <div class="modal-body">      <!--body of modal-->          <!--Form body          <form action="/questions" method="POST">-->          <%=form_for :question,url: '/questions', html: {class: 'form-group'} do %>          <div class="form-group">            <label for="exampleInputEmail1">Email address</label>            <input type="email"  name="question[email]" class="form-control" value = "<%= current_user_email%>" id="exampleInputEmail1" placeholder="Email">          </div>            <div class="form-group">            <label for="inputQuestion" class="control-label">Question:</label>            <textarea class="form-control"  name="question[body]" id="inputQuestion" placeholder="What would you like to know" required=""></textarea>          </div>            <div class="modal-footer">            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>            <button type="submit" class="btn btn-primary">Submit</button>          </div>        <%end%>             <!--body of modal</form>-->  <!--Form body-->        </div>      </div><!-- /.modal-content -->    </div><!-- /.modal-dialog -->  </div><!-- /.modal -->  

From what i can tell it's suppose to identify the modal groups , and modal fade is one of them?

Below here is a sample of the webpage , where i click the green button and a form pops out which is the modal i took from bootstrap.

webpage and modal form

Rails activemodel & actionmailer contact me form returns no route matches [POST]

Posted: 21 Jan 2017 09:53 PM PST

I'm trying to create a 'contact me' form with activemodel to avoid generating needless tables. When I submit the contact form, rails returns the error No route matches [POST] "/contact/new", despite the following routes

config/routes.rb

resources :contact, only: [:new, :create]  

rake routes returns the following...

   contact_index POST   /contact(.:format)                     contact#create     new_contact GET    /contact/new(.:format)                 contact#new  

controller/contact_controller.rb

class ContactController < ApplicationController      def new      @contact = Contact.new    end      def create      @contact = Contact.new(params[:contact])      if @contact.valid?        ContactMailer.contact_submit(@contact).deliver        flash[:notice] = "Thank you for your email, I'll respond shortly"        redirect_to new_contact_path      else        render :new      end    end  end  

mailers/contact_mailer.rb

class ContactMailer < ActionMailer::Base    default to: ENV[EMAIL_ADDRESS]      def contact_submit(msg)      @msg = msg      mail(from: @msg.email, name: @msg.name, message: @msg.message)    end  end  

models/contact.rb

class Contact    include ActiveModel::Validations    include ActiveModel::Conversion    extend ActiveModel::Naming      attr_accessor :name, :email, :message      validates_format_of :email, :with => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i    validates_presence_of :message    validates_presence_of :name      def initialize(attributes = {})      attributes.each do |name, value|        send("#{name}=", value)      end    end      def persisted?      false    end  end  

views/contact/new.html.erb

<%= form_for @contact, url: new_contact_path do |f| %>    <div class="form-inputs">      <div class="form-group">        <%= f.label :name %><br>        <%= f.text_field :name %>      </div>      <div class="form-group">        <%= f.label :email %><br>        <%= f.email_field :email %>      </div>      <div class="form-group">        <%= f.label :message %><br>        <%= f.text_area :message %>      </div>    </div>    <div class="form-actions">      <%= f.submit %>    </div>  <% end %>  

HABTM Association with FactoryGirl

Posted: 22 Jan 2017 05:08 AM PST

Have looked through and tried most examples and still cannot create a working HABTM. No matter how the CaseTrack and CaseTrackValue factories are constructed, I'm not able to find the CaseTrackValue[] in CaseTrack. Shouldn't creating CaseTrack properly provide a CaseTrackValue param within CaseTrack.
BTW: the only working association for HABTM seems to be putting

case_track_values { |a| [a.association(:case_track_value)] } in CaseTrack.

class CaseTrack   has_and_belongs_to_many CaseTrackValue  end    class CaseTrackValue   has_and_belongs_to_many CaseTrack  end    Rspec   it 'may exercise the create action' do    post '<route>', params: {case_track: attributes_for(:case_track)}   end  end    class CaseTrackController < ApplicationController   private:    def case_track_params     params.require(:case_track).permit(:name, :active,   {case_track_values:[]})    end  end  

Can I use an instance method for a computed value in a rails model?

Posted: 22 Jan 2017 01:54 AM PST

I have a model that has a time length (minutes and seconds columns) as part of its data. I would like to add a method to return the time formatted as mm:ss (like 09:08). I've made a method to do this and tested it using irb. But when I try to access the value from my view, it looks like the instance variables are not being initialized and I'm getting "00:00" for all of the values. In looking here and elsewhere, it looks like I could make a class method (by adding self.) and pass the value in for formatting but that seems redundant. The model instance should already have the data. Is using a class method the ruby way? Or am I doing something else obviously wrong?

class Segment  < ApplicationRecord    belongs_to :course      def time      m = pad @min      s = pad @sec      m + ":" + s    end       def pad(x)      x.to_s.rjust(2,"0")    end   end     view:    <%= segment.time %> # returns 00:00    <%= segment.min %>:<%= segment.sec %> # returns correct non-padded values  

I'm using Rails 5.0.1 and Ruby 2.2.6p386.

Rails/Heroku: Cannot find source of ExecJS SyntaxError Unexpected token: eof (undefined)

Posted: 21 Jan 2017 08:23 PM PST

I'm trying to get my assets pipeline set up according to the Heroku guide for Rails 4, but when I enter this at the console:

rake assets:precompile RAILS_ENV=production  

I get this error:

rake aborted!  ExecJS::ProgramError: SyntaxError: Unexpected token: eof (undefined) (line: 46, col: 0, pos: 1394)    Error      at new JS_Parse_Error (<eval>:3623:11948)      at js_error (<eval>:3623:12167)      at croak (<eval>:3623:22038)      at token_error (<eval>:3623:22175)      at unexpected (<eval>:3623:22263)      at block_ (<eval>:3623:28063)      at ctor.body (<eval>:3623:27686)      at function_ (<eval>:3623:27782)      at expr_atom (<eval>:3623:31068)      at maybe_unary (<eval>:3624:1752)  new JS_Parse_Error ((execjs):3623:11948)  js_error ((execjs):3623:12167)  croak ((execjs):3623:22038)  token_error ((execjs):3623:22175)  unexpected ((execjs):3623:22263)  block_ ((execjs):3623:28063)  ctor.body ((execjs):3623:27686)  function_ ((execjs):3623:27782)  expr_atom ((execjs):3623:31068)  maybe_unary ((execjs):3624:1752)  V8::Error: SyntaxError: Unexpected token: eof (undefined)  at js_error (<eval>:3623:12167)  at croak (<eval>:3623:22038)  at token_error (<eval>:3623:22175)  at unexpected (<eval>:3623:22263)  at block_ (<eval>:3623:28063)  at ctor.body (<eval>:3623:27686)  at function_ (<eval>:3623:27782)  at expr_atom (<eval>:3623:31068)  at maybe_unary (<eval>:3624:1752)  at expr_ops (<eval>:3624:2523)  at maybe_conditional (<eval>:3624:2615)  at maybe_assign (<eval>:3624:3058)  at expression (<eval>:3624:3384)  at expr_list (<eval>:3623:31548)  at subscripts (<eval>:3624:1461)  at expr_atom (<eval>:3623:31132)  at maybe_unary (<eval>:3624:1752)  at expr_ops (<eval>:3624:2523)  at maybe_conditional (<eval>:3624:2615)  at maybe_assign (<eval>:3624:3058)  at expression (<eval>:3624:3384)  at expr_atom (<eval>:3623:30820)  at maybe_unary (<eval>:3624:1752)  at expr_ops (<eval>:3624:2523)  at maybe_conditional (<eval>:3624:2615)  at maybe_assign (<eval>:3624:3058)  at expression (<eval>:3624:3384)  at simple_statement (<eval>:3623:25942)  at <eval>:3623:23902  at <eval>:3623:22954  at <eval>:3624:3759  at parse (<eval>:3624:3999)  at parse (<eval>:3958:22)  at uglifier (<eval>:4003:13)  Tasks: TOP => assets:precompile  

I have seen other posts on SO with similar errors like this and this, but in both of those cases, the error was nice enough to say which file the error was in. In my error, I don't see a reference to the actual file, so I'm stumped on where to go from here.

Looking back, when I started trying to fix this, it DID show a file (or something), but I can't make heads or tails of it (nor do I know why it stopped showing the location of the error...):

Error      at new JS_Parse_Error (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:11948)      at js_error (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:12167)      at croak (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:22038)      at token_error (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:22175)      at unexpected (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:22263)      at block_ (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:28063)      at /private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:27686      at function_ (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:27782)      at expr_atom (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3623:31068)      at maybe_unary (/private/var/folders/hz/1d1f64ln59b4_pl632lm6mpr0000gn/T/execjs20170121-47471-7jr3eejs:3624:1752)  new JS_Parse_Error ((execjs):3623:11948)  js_error ((execjs):3623:12167)  croak ((execjs):3623:22038)  token_error ((execjs):3623:22175)  unexpected ((execjs):3623:22263)  block_ ((execjs):3623:28063)  (execjs):3623:27686  function_ ((execjs):3623:27782)  expr_atom ((execjs):3623:31068)  maybe_unary ((execjs):3624:1752)  

I looked in the directory mentioned there and see no relevant files. I searched my whole system for "execjs20170121-47471-7jr3ee" and "execjs20170121-47471-7jr3eejs" with no luck.

From what I've read in the other posts, it looks like Uglifier is erroring out while parsing my Javascript, but again, I just don't know where to look to try to fix it.

Any ideas?

Can you pass a _tag as a rails helper argument?

Posted: 22 Jan 2017 05:51 AM PST

I have two form field types (f.text_field or f.text_area) that I want to define through a helper:

def helper_thing(tagtype, field_id)    tagtype("#{field_id}", class: 'input-group-field')  end  

I want to use tagtype as a variable for either form text helper in the view (using haml):

= helper_thing(f.text_field, 'random_id')  

I'm hoping the output would be something like:

f.text_field('random_id')  

I always get an error saying "invalid number of args 0 of 1..3)" essentially causing the rest of my arguments to fail. For the sake of brevity I only used one argument in my example though.

Is what I'm trying to do possible?

How can i set an Order in a Rail's Jbuilder JSON

Posted: 21 Jan 2017 08:00 PM PST

I'm developing an simple invoicing app in Rails 5

For this question I have 2 models.

Quote

class Quote < ApplicationRecord    belongs_to :client, optional: true    has_many :quote_items, dependent: :destroy    accepts_nested_attributes_for :quote_items  end  

And QuoteItem

class QuoteItem < ApplicationRecord    default_scope { order(:id, :item_order) }      belongs_to :quote  end  

Because i have a scope in the QuoteItem model I can display the data in my erb based in the item_order field.

But now i need to use the same data in JSON for build a dynamic table. And the Scope in my QuoteItem model is not working with Jbuilder.

This is the JSON format:

#myapp/app/views/quotes/show.json.jbuilder    json.quote do    json.partial! "quotes/quote", quote: @quote      json.quote_items do    json.array!(@quote.quote_items) do |item|      json.id item.id      json.clave item.product.clave      json.name item.name      json.quantity item.quantity      json.item_order item.item_order      json.days item.days      json.unit_price item.unit_price      json.seguro item.seguro      json.descuento item.descuento      json.total item.total  end    end  end  

My question is How can I set the sort order of json.quote_items with the "item_order" field instead of his "id".

Rails not translating to spanish

Posted: 22 Jan 2017 02:10 AM PST

I'm trying to translate a db record to spanish. I have an article.created_at.strftime("%b.") which display "January" but I want it to display "Enero" (spanish for January).

So, I have " gem 'rails-i18n', '~> 4.0.0' " on my gemfile, (I also have tried with gem 'i18n', '~> 0.7.0'). but It doesn't seem to work for me. I understand that I should use l (for localize) like this:

<%=  l(article.created_at, format: '%b.') %>  

But the only thing i get is a message "We're sorry, but something went wrong."

I have read several question similar for this, like this or this. But it doesn't work for me... any idea what I'm missing? Thank you!

Permission denied accessing api from emulator using ionic, ng_token_auth and devise_token_auth

Posted: 21 Jan 2017 07:49 PM PST

I have an issue thats killing me. I've got an ionic app that authenticates the user with my rails web app through a rails 5 api using devise_token_auth, ng_token_auth and facebook omniauth. The whole process works fine when using ionic serve, however using ionic emulate or when building in xcode the authentication process fails. I see two permission related errors:

xcode: 2017-01-22 08:23:13.349 locationTrack[59058:1038068] Finished load of: https://m.facebook.com/login.php?skip_api_login=1&api_key=1449618985293519&signed_next=1&next=https%3A%2F%2Fm.facebook.com%2Fv2.6%2Fdialog%2Foauth%3Fredirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fomniauth%252Ffacebook%252Fcallback%26state%3D366b5ee9d59d6a9f89a42abc644f0c6923f97aeee4ae2e8f%26scope%3Demail%26response_type%3Dcode%26client_id%3D1449618985293519%26ret%3Dlogin%26logger_id%3D7956d538-e809-46f0-b9dd-e302db4978cb&cancel_url=http%3A%2F%2Flocalhost%3A3000%2Fomniauth%2Ffacebook%2Fcallback%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3D366b5ee9d59d6a9f89a42abc644f0c6923f97aeee4ae2e8f%23_%3D_&display=touch&locale=en_GB&logger_id=7956d538-e809-46f0-b9dd-e302db4978cb&_rdr

safari: Failed to load resource: You do not have permission to access the requested resource. http://localhost:3000//auth/facebook/callback

Notice the double slash in the url above. Not sure where this is coming from but doubting its the cause of the issue.

The error occurs when the ionic app receives the response from the api. Verified by the fact i can see the authentication take place on the rails api and the user creds passed back.

Due to the fact that it works on ionic serve i'm guessing this must be something to do with either the cordova permissions or the fact that the rails 5 api isn't configured to allow access via an app without an ip?

I've therefore tried also using the cordova whitelist plugin. Whitelisting all ips, and completely opening up the permissions on the api using Rack-Cors gem.

I've googled the sh*t out of this and am completely stumped. Code snippets below:

In my ionic app

app.js

.config(function($authProvider) {      $authProvider.configure({        apiUrl: 'http://localhost:3000',        storage: 'localStorage'      });  })    .config(function($stateProvider, $urlRouterProvider) {    $stateProvider    .state('auth', {      url: "/auth",      templateUrl: "views/auth.html",      abstract: true,    })    .state('auth.welcome', {      url: '/welcome',      templateUrl: "views/welcome.html",      controller: 'WelcomeCtrl'    })    .state('dashboard', {      url: '/dashboard',      templateUrl: "views/dashboard.html",      controller: 'DashboardCtrl',    })      ;    // if none of the above states are matched, use this as the fallback    $urlRouterProvider.otherwise('/auth/welcome');  })  

welcome controller - redirect on auth.

  $auth.validateUser().then(function(resp) {      console.log('validated User');      $window.location.href = '/#/dashboard';      // $state.go('dashboard');    });  

config.xml

  <allow-navigation href="*" />    <allow-intent href="*" />    <access origin="*" />  

index.html - content security meta

<meta http-equiv="Content-Security-Policy" content="default-src data: gap: * http://localhost:3000; script-src 'self' 'unsafe-inline' 'unsafe-eval' data: gap: https://ssl.gstatic.com *; style-src  'self' 'unsafe-inline' *">  

In My Rails 5 API

routes.rb

mount_devise_token_auth_for 'User', at: 'auth'  

users_controller.rb

before_filter :authenticate_user!, except: [:new, :create]  

devise_token_auth.rb

 (default settings)  

omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do    provider :facebook, "XXX", "XXX"  end  

rack cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do    allow do      origins '*'        resource '*',        headers: :any,        methods: [:get, :post, :put, :patch, :delete, :options, :head]    end  end  

rack_attack.rb

class Rack::Attack      # `Rack::Attack` is configured to use the `Rails.cache` value by default,    # but you can override that by setting the `Rack::Attack.cache.store` value    Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new      # Allow all local traffic    safelist('allow-localhost') do |req|      '*' == req.ip || '::1' == req.ip    end      # Allow an IP address to make 5 requests every 5 seconds    throttle('req/ip', limit: 5, period: 5) do |req|      req.ip    end      # Send the following response to throttled clients    self.throttled_response = ->(env) {      retry_after = (env['rack.attack.match_data'] || {})[:period]      [        429,        {'Content-Type' => 'application/json', 'Retry-After' => retry_after.to_s},        [{error: "Throttle limit reached. Retry later."}.to_json]      ]    }  end  

All help or hints much appreciated in advance!

Saturday, January 21, 2017

Rails Admin: display a has many association with checkboxes | Fixed issues

Rails Admin: display a has many association with checkboxes | Fixed issues


Rails Admin: display a has many association with checkboxes

Posted: 21 Jan 2017 07:44 AM PST

Rails Admin displays the has_many association as a couple of boxes like this:

rails admin selector

Instead, I would like to show simple checkboxes.

How can I achieve that?

How to know plain text of :encrypted_password, in devise?

Posted: 21 Jan 2017 07:30 AM PST

If i use has_secure_password, i have whitelist are: password, password_confirmation, and password_digest. With password is the plain text of password_digest, which was encrypted by bcrypt.

But when i use devise with my user model, it has only encrypted_password field, I don't know how to know plain text of password. The schema doesn't has password field. I uasually use rails consle to debug. So anyone can help me how to know the plain text of encrypted_password.

gem pg destroyed my app

Posted: 21 Jan 2017 07:01 AM PST

UserXs-MacBook-Pro:shobiz Ayaz$ rails s  => Booting Puma  => Rails 5.0.1 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  Exiting  /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/puma/launcher.rb:328:in `stat': No such file or directory @ rb_file_s_stat - /Users/userx/Desktop/shobiz (Errno::ENOENT)      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/puma/launcher.rb:328:in `generate_restart_data'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/puma/launcher.rb:66:in `initialize'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/rack/handler/puma.rb:47:in `new'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/puma-3.6.2/lib/rack/handler/puma.rb:47:in `run'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/server.rb:296:in `start'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/server.rb:79:in `start'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:90:in `block in server'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'      from /Users/userx/Desktop/showbiz/bin/rails:9:in `require'      from /Users/userx/Desktop/showbiz/bin/rails:9:in `<top (required)>'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `load'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `call'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client/command.rb:7:in `call'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/client.rb:30:in `run'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/bin/spring:49:in `<top (required)>'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `load'      from /Users/userx/.rvm/gems/ruby-2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `<top (required)>'      from /Users/userx/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /Users/userx/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /Users/userx/Desktop/showbiz/bin/spring:14:in `<top (required)>'      from bin/rails:3:in `load'      from bin/rails:3:in `<main>'  

It was my first time to upload app on heroku I have installed gem pg. but now unable to run rails server and getting these type error

Rails delayed job and docker: adding more workers

Posted: 21 Jan 2017 06:57 AM PST

I run my rails app using a Docker. Now delayed jobs are processed by a single worker that runs in a separate contariner called worker and it runs with a command bundle exec rake jobs:work.

I have several types of jobs that I would move to a separate queue and create a separate worker for that or at least have two workers for process tasks. I tested run my worker container with env QUEUE=default_queue bundle exec rake job:work && env QUEUE=another_queue bundle exec rake job:work bit that do not make any sense. It does not fails, is starts but jobs aren't processed. Is there any way to have separate workers in one container? And is it correct? Or should I create separate container for each worker I would ever want to make?

Thanx in advance!

Redmine : rake aborted due to "existent table "when installing "wk-time" Plugin

Posted: 21 Jan 2017 06:34 AM PST

I'm trying to install the "ERPmine" plugin :

Official documentation : http://www.redmine.org/plugins/wk-time

As the documentation says , and like every plugin i'm used to do the following :

  1. importing this pugin to the /redmine/plugins
    (successfull)
  2. running: bundle install (successfull)
  3. updating the schema of the database by running this : (aborted)

    rake redmine:plugins:migrate NAME=redmine_wktime RAILS_ENV=production

the error syas that there is a tbale which is already created "Table 'wk_addresses' already exists"

there is some blogs which talked on updating the DB , by executing this :

rake db:migrate RAILS_ENV=production  

but the plugin set up still failing ; the complete error is that :

== 5 CreateWkBilling: migrating ===============================================  -- create_table(:wk_addresses)  rake aborted!  StandardError: An error has occurred, all later migrations canceled:    Mysql2::Error: Table 'wk_addresses' already exists: CREATE TABLE `wk_addresses` (`id` int(11) auto_increment PRIMARY KEY, `address1` varchar(255), `address2` varchar(255), `work_phone` varchar(255), `home_phone` varchar(255), `mobile` varchar(255), `email` varchar(255), `fax` varchar(255), `city` varchar(255), `country` varchar(255), `state` varchar(255), `pin` int(11), `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'  /var/lib/gems/2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:222:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:474:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:665:in `block in method_missing'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'  /opt/redmine/plugins/redmine_wktime/db/migrate/005_create_wk_billing.rb:3:in `change'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:768:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:1046:in `ddl_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:959:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `each'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:823:in `up'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:801:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:481:in `migrate_plugin'  /opt/redmine/lib/redmine/plugin.rb:453:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:464:in `migrate'  /opt/redmine/lib/tasks/redmine.rake:127:in `block (3 levels) in <top (required)>'  /var/lib/gems/2.1.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'  ActiveRecord::StatementInvalid: Mysql2::Error: Table 'wk_addresses' already exists: CREATE TABLE `wk_addresses` (`id` int(11) auto_increment PRIMARY KEY, `address1` varchar(255), `address2` varchar(255), `work_phone` varchar(255), `home_phone` varchar(255), `mobile` varchar(255), `email` varchar(255), `fax` varchar(255), `city` varchar(255), `country` varchar(255), `state` varchar(255), `pin` int(11), `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'  /var/lib/gems/2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:222:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:474:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:665:in `block in method_missing'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'  /opt/redmine/plugins/redmine_wktime/db/migrate/005_create_wk_billing.rb:3:in `change'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:768:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:1046:in `ddl_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:959:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `each'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:823:in `up'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:801:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:481:in `migrate_plugin'  /opt/redmine/lib/redmine/plugin.rb:453:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:464:in `migrate'  /opt/redmine/lib/tasks/redmine.rake:127:in `block (3 levels) in <top (required)>'  /var/lib/gems/2.1.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'  Mysql2::Error: Table 'wk_addresses' already exists  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'  /var/lib/gems/2.1.0/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `block in execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:484:in `block in log'  /var/lib/gems/2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_adapter.rb:478:in `log'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:309:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/schema_statements.rb:222:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:474:in `create_table'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:665:in `block in method_missing'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `block in say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:634:in `say_with_time'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:654:in `method_missing'  /opt/redmine/plugins/redmine_wktime/db/migrate/005_create_wk_billing.rb:3:in `change'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:608:in `exec_migration'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:591:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:590:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:768:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:1046:in `ddl_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:959:in `block in migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `each'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:955:in `migrate'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:823:in `up'  /var/lib/gems/2.1.0/gems/activerecord-4.2.7.1/lib/active_record/migration.rb:801:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:481:in `migrate_plugin'  /opt/redmine/lib/redmine/plugin.rb:453:in `migrate'  /opt/redmine/lib/redmine/plugin.rb:464:in `migrate'  /opt/redmine/lib/tasks/redmine.rake:127:in `block (3 levels) in <top (required)>'  /var/lib/gems/2.1.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'  Tasks: TOP => redmine:plugins:migrate  (See full trace by running task with --trace)  

Any suggestions ??

Redmine - 501 Syntactically invalid HELO argument(s)

Posted: 21 Jan 2017 06:00 AM PST

Installed redmine on remote server(ubuntu)

In redmine i want test mail(Setting-email notification). Get error:

An error occurred while sending mail (501 Syntactically invalid HELO argument(s) )

I have following setting mail:

config/configuration.yml

default:    email_delivery:      delivery_method: :smtp      smtp_settings:        address: "mail.name.com"        port: 25        authentication: :login        domain: 'xxx.xx.xx.xx:81'        user_name: 'office@mail.com'        password: 'xxxxxxxx'        enable_starttls_auto: false        openssl_verify_mode: 'none'  

etc/hosts

127.0.0.1       localhost h997VM  xxx.xx.xx.xxx   ubuntu14gi    # The following lines are desirable for IPv6 capable hosts  ::1     localhost ip6-localhost ip6-loopback  ff02::1 ip6-allnodes  ff02::2 ip6-allrouters  

etc/hostname

h997VM  

Information about system:

Ubuntu 14  Environment:    Redmine version                3.3.2.devel    Ruby version                   2.3.1-p112 (2016-04-26) [x86_64-linux]    Rails version                  4.2.7.1    Environment                    production    Database adapter               PostgreSQL  

What could be the reason? An how fix? Thank for advance for your help.

Using Wikipedia-Client Gem to Update Rails Database

Posted: 21 Jan 2017 05:53 AM PST

My ruby and Rails is a bit rusty. I have a table in my database called institutes which has some of the columns filled. I want to use the Wikipedia-Client gem to fill some of the others. I want to use the name attribute to find the page on Wikipedia then use page.summary for the description attribute in my table and page.image_urls.first for the picture attribute. At the moment, I'm struggling to work out how I would go about this.

My current code is:

require 'Wikipedia'  Institute.each do |institute|     school = institute.pluck(:name)     page = Wikipedia.find(school)     description = page.summary     picture = page.image_urls.first     Institute.update!(description: description, picture: picture)  end  

I'm clearly doing something wrong here to do with the selection and use of the name attribute to find the Wikipedia page, but can't quite work it out. I think even if I were to pluck the name correctly, it wouldn't assign anything to the right id.

If there's also a way to drop the "The" at the beginning of the name in the Wikipedia search if it exists in :name, that would also be helpful as it seems some institutes drop this on Wikipedia.

Setup react-routing with rails app

Posted: 21 Jan 2017 05:26 AM PST

I am newbie for React, I know rails, I have created basic React application that perform CRUD operation.

Now, I tried to implement routing with react and want to redirect a page after successful login.

I have used gem 'react-rails' and gem 'react-router-rails' in my app.

Please instruct me with basic step to setup react route.

Thanks in advance.

using prepend_view_path to manage multiple domains on same app

Posted: 21 Jan 2017 05:02 AM PST

I'm trying to run several domains on my rails app where a lot of the view codes is shared. In order to do this I've created the following directory structure

- views      - shared      - domain1      - domain2  

I'ved added a before_filter in my application controller like so

before_filter :add_domain_view_paths    def add_domain_view_paths    prepend_view_path "app/views/shared"    prepend_view_path "app/views/#{app_domain}"  end  

After making this change and moving all current views into the app/views/shared my app suddenly started to slow down and also leak memory. No other changes were made at the time

This graph shows response times before and after making the change enter image description here Performance also seems to degrade when leaving the views in their original app/views/controller_name folder and only including the include filter as I've described above. Though there still seems to be a memory leak originating from this before_filter.

What am I doing wrong?

Rails; Fetch records within initializer

Posted: 21 Jan 2017 05:23 AM PST

I've been wondering it is common to fetch records within initializer?

Here this is an example for service object to fetch records and generated pdf receipt file.

Input is invoice uuid, and fetch the related records such as card detail, invoice items within initialier.

    class Pdf::GenerateReceipt        include Service          attr_reader :invoice, :items, :card_detail          def initialize(invoice_uuid)          @invoice ||= find_invoice!(invoice_uuid) # caching          @items = invoice.invoice_items          @card_detail = card_detail        end        .....          def call          return ReceiptGenerator.new(            id: invoice.uuid, # required            outline: outline, # required            line_items: line_items, # required            customer_info: customer_info          )         rescue => e          false, e        end         .....          def card_detail          card_metadata = Account.find(user_detail[:id]).credit_cards.primary.last            card_detail = {}          card_detail[:number] = card_metadata.blurred_number          card_detail[:brand] = card_metadata.brand          card_detail        end     end    Pdf::GenerateReceipt.('28ed7bb1-4a3f-4180-89a3-51cb3e621491') # => then generate pdf  

The problem is if the records not found, this generate an error. I could rescue within the initializer, however that seems not common.

How could I work around this in more ruby way?

missing requiered keys: [:post_id], add comments to post on a page with many posts

Posted: 21 Jan 2017 07:15 AM PST

I'm trying to add comments to my posts. When I have done that successfully before I cannot get it right now. The problem is that I have lots of posts on the same page, all of them with a comment box underneath (much like any social network).

However the page will not even render displaying this error:

No route matches {:action=>"new", :controller=>"comments", :post_id=>nil} missing required keys: [:post_id]  

Although its sending the right project id, it cannot find the post_id as there are many posts on the page (I think thats the problem... right?).

Please see below my associations:

routes.rb

  resources :projects do      resources :comments, :posts    end      resources :posts do       resources :comments    end  

Models

class Project < ApplicationRecord    belongs_to :user    has_many :comments, dependent: :destroy    has_many :posts, dependent: :destroy    class Post < ApplicationRecord    belongs_to :user    belongs_to :project    has_many :comment, dependent: :destroy    class Comment < ApplicationRecord    belongs_to :user    belongs_to :project    belongs_to :post  

Form

<%= form_for(@post, new_post_comment_path(@post)) do |f| %>  

comments controller

class CommentsController < ApplicationController    before_action :find_post    def create      @project = Project.find(params[:project_id])    @post = Post.find(params[:post_id])    @comment = current_user.comments.build(comment_params)    @comment.user_id = current_user.id         if @comment.save        flash[:success] = "Comment created!"        redirect_to @project      else        @projectboard_items = []        flash[:danger] = "Sorry! your comment was not created"        redirect_to :back      end    end       private      def find_post      @post = Post.find(params[:post_id])    end  

Thanks in advance!

Rails 5 - vendor assets are not loaded on production (fonts only)

Posted: 21 Jan 2017 06:31 AM PST

It's perfectly working in development, but not in production. It's not finding the following files:

/assets/fontello.woff
/assets/fontello.ttf

Here is the setup:

  1. fonts files:

enter image description here

  1. assets.rb

    Rails.application.config.assets.paths << Rails.root.join('app', 'vendor', 'assets', 'fonts')  Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/  
  2. fontello.css

    @font-face {    font-family: 'fontello';      src: url('/assets/fontello.eot');      src: url('/assets/fontello.eot#iefix') format('embedded-opentype'),      url('/assets/fontello.woff') format('woff'),      url('/assets/fontello.ttf') format('truetype'),      url('/assets/fontello.svg#fontello') format('svg');    font-weight: normal;    font-style: normal;  }  

As I said, everything is working fine in development. I have try a lot of things. For example:

  1. moving the fonts in the public folder (as my images there are loaded)
  2. add the following line in the assets.rb:

    Rails.application.config.assets.precompile += [/^[-_a-zA-Z0-9]*\..*/]  

but nothing worked.

Could you advise anything else to try?

Bundler trying to install development gems in production

Posted: 21 Jan 2017 04:03 AM PST

When I try to deploy my Rails 5 application using Capistrano 3, it tries to install development gems even in staging. This is completely new behaviour and I have no idea where it's coming from (came in the middle of a bunch of commits to a controller, the deploy scripts or Gemfile weren't touched at all).

The relevant lines of the capistrano.log are:

bash: line 1: 13108 Killed /path/to/my/app/rvm1scripts/rvm-auto.sh 2.4.0 bundle install --path /path/to/my/app/shared/bundle --without development test --deployment --quiet  bundle stderr: Nothing written  ** DEPLOY FAILED  ** Refer to log/capistrano.log for details.  

My capistrano.log can be found at this gist, but the gist of it is that it checks the bundle, which fails because the group :development gems aren't installed (obviously), and then tries to bundle install, which won't happen because they're in the development group. It's a weird, cyclical problem.

Heroku code=H10 app crashed

Posted: 21 Jan 2017 05:29 AM PST

I am new to Heroku and rails. I've read articles to create APIs for my phone app.

I have succeeded in creating locally and when I run server, the APIs respond correctly, but when I try to use the heroku link to my app I get error in log\console saying

at=error code=H10 desc="App crashed" method=GET path="/api/v1/carbrands/" host=b-taxi-server.herokuapp.com request_id=283223f5-f68d-4c4a-bb70-3346a2e3327f fwd="156.205.91.128" dyno= connect= service= status=503 bytes=    at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=b-taxi-server.herokuapp.com request_id=10510255-6149-4583-8886-6bbb69f37aaa fwd="156.205.91.128" dyno= connect= service= status=503 bytes=    /app/app/controllers/Api/V1/carbrands_controller.rb:1:in `<top (required)>': uninitialized constant Api (NameError)          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:472:in `block (2 levels) in eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:471:in `each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:471:in `block in eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:469:in `each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:469:in `eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/engine.rb:346:in `eager_load!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:56:in `each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:56:in `block in <module:Finisher>'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `instance_exec'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `run'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:55:in `block in run_initializers'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `call'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'          from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/initializable.rb:54:in `run_initializers'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application.rb:352:in `initialize!'          from /app/config/environment.rb:5:in `<top (required)>'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/application.rb:328:in `require_environment!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:142:in `require_application_and_environment!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:67:in `console'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'          from bin/rails:4:in `require'          from bin/rails:4:in `<main>'  

Carbrands controller is under $$\app\controllers\Api\V1\carbrands_controller.rb

I've controller carbrands_controller.rb which has following

class Api::V1::CarbrandsController < ApplicationController    respond_to :json    skip_before_filter :verify_authenticity_token      def index          output_brands       end        def output_brands        brands = CarBrand.all        #@trips = Trip.all        if brands          respond_to do |format|          format.html          format.json { render :json => brands.to_json, status: status } #see if you want to send the cars for each user or not          end        else          output_error(401, @noBrands_found)        end            end    end  

in my routes I have

Rails.application.routes.draw do    #api routes path    #devise_for :users    namespace :api, defaults: { format: :json } do      namespace :v1 do        resources :carbrands,  only: [:create, :index]      end    end  end  

I am not sure what is wrong to be honest. I've pushed the code using git push heroku master

How do I fix that error?

How do I go about adding business_day, opening_time, and closing_time to my app?

Posted: 21 Jan 2017 03:59 AM PST

What I want to accomplish in my form is like that of the Hours field in the yelp's business form where a user can set an opening and closing time for a specific day.

Do I have to add a column through migration let's say business_time, opening_time, closing_time or there's a gem for this? Can someone point me to the right direction?

Scraping HTML table with Nokogiri and saving to database

Posted: 21 Jan 2017 03:49 AM PST

I've been trying to scrape a website for education information to save to my app database. The site has a three column table as follows:

<thead>  <tr height="20">  <th height="20" scope="col" width="91">UKPRN</th>  <th scope="col" width="87">INSTID</th>  <th scope="col" width="264">Name</th>  </tr>  </thead>  <tbody>  <tr height="20">  <td height="20">10000291</td>  <td>0047</td>  <td>Anglia Ruskin University</td>  </tr>  <tr height="20">  <td height="20">10007759</td>  <td>0108</td>  <td>Aston University</td>  </tr>  <tr height="20">  <td height="20">10000571</td>  <td>0048</td>  <td>Bath Spa University</td>  </tr>  <tr height="20">  <td height="20">10007850</td>  <td>0109</td>  <td>The University of Bath</td>  </tr>  <tr height="20">  <td height="20">10007152</td>  <td>0026</td>  <td>University of Bedfordshire</td>  </tr>  <tr height="20">  <td height="20">10007760</td>  <td>0127</td>  <td>Birkbeck College</td>  </tr>  <tr height="20">  <td height="20">10007140</td>  <td>0052</td>  <td>Birmingham City University</td>  </tr>  <tr height="20">  <td height="20">10006840</td>  <td>0110</td>  <td>The University of Birmingham</td>  </tr>  

and so on. I want to get the 8 figure reference, the 4 figure reference and the school name saved to my database under UKPRN, instid and name respectively.

This is the only table on the page so is easy to grab. So far my code in irb looks like this:

require 'nokogiri'  require 'open-uri'    page = Nokogiri::HTML(open(url))  rows = data.css("tr")  rows.each do |row|     name = row.css("td")[2]     ukprn = row.css("td")[0]     instid = row.css("td")[1]  end  

This seems to work ok as when I print one of the variables it seems to pick up the right data, but I can't get rid of the tags around the text, and once done, I'm not sure how I would go about saving this data to my institute model in the database. The attributes should correlate with the names given above. Any help is appreciated.

Condition on mount_uploader Carrierwave

Posted: 21 Jan 2017 02:30 AM PST

I have user model and have multiple method of signup : via form, with facebook & with gmail. User model have user_picture attribute and it mount to uploader using carrierwave. I won't to upload picture of user if their login with facebook or google but only save url picture from facebook or google. How can I use conditional on mount_uploader if user signup with facebook or google?

class User    mount_uploader :user_picture, UserPictureUploader # I try this condition but not working :if => Proc.new{|u| u.provider.blank? }   end  

Should I add another attribute for save picture from provider? I think that's bad practice, I want to use single attribute.

Rails Associations - undefined method for nil:NilClass

Posted: 21 Jan 2017 01:41 AM PST

Basic question on Rails associations with the following tables:

  • Shop: name, network
  • Product: title, price, shop_id

Relation defined as has_many and belongs_to:

Model:

shop.rb

class Shop < ApplicationRecord      has_many   :products  end  

product.rb

class Product < ApplicationRecord       self.primary_key = "id"       belongs_to :shop  end  

Controller:

shops_controller.rb

  def show      @shop = Shop.find(params[:id])   end  

products_controller.rb

  def show      @product = Product.find(params[:id])    end  

In the Shop view I manage to reference and show all Products for each Shop without problems:

<%= @shop.name %>  <%= @shop.network %>      <% @shop.products.each do |product| %>     <%= product.title %>    <% end %>  

But the other way around in the Product view I don't manage to show the network information from the Shop table :

  <%= @product.title %>    <%= @product.shop.network %>  

This returns the following error:

undefined method `network' for nil:NilClass  

gem install mysql2 does not work

Posted: 21 Jan 2017 01:54 AM PST

I'm trying to install mysql2 gem to use in learning rails, but it just doesn't work. Reinstalling mysql or ruby doesn't work. Using ARCHFLAGS doesn't work. I can't use apt-get libmysqlclient-dev because my Mac doesn't have Ubuntu server, and anyways wouldn't this be a dependency included in mysql when installed with homebrew (as I've done)? Also I have the very latest Xcode (8.2.1). This is the complete error message (with username in place of actual user name):

Building native extensions.  This could take a while...  ERROR:  Error installing mysql2:      ERROR: Failed to build gem native extension.        current directory: /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/ext/mysql2  /Users/username/.rbenv/versions/2.3.1/bin/ruby -r ./siteconf20170121-4906-1lcyftl.rb extconf.rb  checking for rb_absint_size()... yes  checking for rb_absint_singlebit_p()... yes  checking for ruby/thread.h... yes  checking for rb_thread_call_without_gvl() in ruby/thread.h... yes  checking for rb_thread_blocking_region()... no  checking for rb_wait_for_single_fd()... yes  checking for rb_hash_dup()... yes  checking for rb_intern3()... yes  checking for rb_big_cmp()... yes  -----  Using mysql_config at /usr/local/bin/mysql_config  -----  checking for mysql.h... yes  checking for SSL_MODE_DISABLED in mysql.h... yes  checking for SSL_MODE_PREFERRED in mysql.h... yes  checking for SSL_MODE_REQUIRED in mysql.h... yes  checking for SSL_MODE_VERIFY_CA in mysql.h... yes  checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes  checking for errmsg.h... yes  checking for mysqld_error.h... yes  -----  Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load  -----  -----  Setting libpath to /usr/local/Cellar/mysql/5.7.17/lib  -----  creating Makefile    To see why this extension failed to compile, please check the mkmf.log which can be found here:      /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0-static/mysql2-0.4.5/mkmf.log    current directory: /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/ext/mysql2  make "DESTDIR=" clean    current directory: /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5/ext/mysql2  make "DESTDIR="  compiling client.c  compiling infile.c  compiling mysql2_ext.c  compiling result.c  compiling statement.c  linking shared-object mysql2/mysql2.bundle  ld: library not found for -lssl  clang: error: linker command failed with exit code 1 (use -v to see invocation)  make: *** [mysql2.bundle] Error 1    make failed, exit code 2    Gem files will remain installed in /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/mysql2-0.4.5 for inspection.  Results logged to /Users/username/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-16/2.3.0-static/mysql2-0.4.5/gem_make.out  

The commands I tried to install mysql2 were:

gem install mysql2  sudo gem install mysql2 (if the error was permission denied.)  sudo gem install mysql2 -v '0.4.5' -- --with-mysql-config=/usr/local/Cellar/mysql/5.7.17/bin/mysql_config  ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future sudo gem install mysql2 -v '0.4.5'  

Not sure what exactly those mean, as I did them following advice from similar posts.

Please help. Thanks!

Dynamically include associations for objects in Rails

Posted: 21 Jan 2017 01:28 AM PST

I am currently developing a small Rails 5 application where I need to pass on an ActiveRecord object to an external service based on certain events. In my model I have defined the following:

# /models/user.rb  after_create :notify_external_service_of_user_creation    def notify_external_service_of_user_creation    EventHandler.new(      event_kind: :create_user,      content: self    )  end  

The EventHandler is then converting this object to JSON and is sending it through an HTTP request to the external service. By calling .to_json on the object this renders a JSON output which would look something like this:

{    "id":1234,    "email":"test@testemail.dk",    "first_name":"Thomas",    "last_name":"Anderson",    "association_id":12,    "another_association_id":356  }  

Now, I need a way to include all first level associations directly into this, instead of just showing the foreign_key. So the construct I am looking for would be something like this:

{    "id":1234,    "email":"test@testemail.dk",    "first_name":"Thomas",    "last_name":"Anderson",    "association_id":{      "attr1":"some_data",      "attr2":"another_value"    },    "another_association_id":{      "attr1":"some_data",      "attr2":"another_value"    },  }  

My first idea was to reflect upon the Model like so: object.class.name.constantize.reflect_on_all_associations.map(&:name), where object is an instance of a user in this case, and use this list to loop over the associations and include them in the output. This seems rather tedious though, so I was wondering if there would be a better way of achieving this using Ruby 2.4 and Rails 5.

how to test json using swagger

Posted: 20 Jan 2017 11:19 PM PST

I have created a json which returns a account info. I am trying to test it on swagger. This is what i did so far:

  1. downloaded zip folder from the location below

https://github.com/swagger-api/swagger-ui

  1. copied dist folder from zip and put in public folder of my project.

But when i do localhost:3001/dist/index.html, it wont show the action i have in controller.

can someone direct me what i am doing wrong or direct me to any online article?

Thanks

Passenger error: Could not spawn process for application /home/user/app/current

Posted: 20 Jan 2017 10:48 PM PST

I'm setting up a Rails app using Nginx and Passenger on Digital Ocean, but I'm getting an error when visiting the IP address.

We're sorry, but something went wrong.

I can confirm the directory being referenced because I can navigate there and run pwd. => ~/app/current/public/assets

Error Log: /var/log/nginx/error.log

  Could not spawn process for application       /home/<user>/<app>/current: An error occurred while starting up the preloader.    Error ID: 1bb1fce1    Error details saved to: /tmp/passenger-error-vZPTxi.html    Message from application: Unable to autoload constant      API::Mobile::V1::BaseApiController, expected       /home/<user>/<app>/releases/20170121053748/app/controllers/api/mobile/v1/base_api_controller.rb       to define it (LoadError)  

*There is more information in a passenger-error...html file but it was very verbose so I didn't know what to include from it.

/sites-available/default:

server {          listen 80;          listen [::]:80 ipv6only=on;            server_name 127.0.0.1;          passenger_enabled on;          rails_env production;            root /home/<user>/<app>/current/public;            error_page 500 502 503 504 /50x.html;          location = /50x.html {                  root html;          }          index index.html index.htm index.nginx-debian.html;            server_name _;            location / {                  try_files $uri $uri/ =404;          }  }  

nginx.conf

user www-data;  worker_processes auto;  pid /run/nginx.pid;    events {          worker_connections 768;  }  http {          sendfile on;          tcp_nopush on;          tcp_nodelay on;          keepalive_timeout 65;          types_hash_max_size 2048;            include /etc/nginx/mime.types;          default_type application/octet-stream;            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;           ssl_prefer_server_ciphers on;            access_log /var/log/nginx/access.log;          error_log /var/log/nginx/error.log;            gzip on;          gzip_disable "msie6";            include /etc/nginx/passenger.conf;            include /etc/nginx/conf.d/*.conf;          include /etc/nginx/sites-enabled/*;  }  

I've seen similar questions on SO but the answers weren't able to help so far.

Is there a common solution to this?

searchkick re indexing not working on rails application production

Posted: 21 Jan 2017 01:41 AM PST

Im trying to use Searchkick in my application. However, I get

Searchkick::MissingIndexError   Index missing - run Restaurant.reindex  

I run Restaurant.reindex but it didn't solve the issue. I also tried the following: rake searchkick:reindex:all and I receive the Reindex complete message; however,I come up with the same missing index error when I submit the search query.

Do I need to deploy my rails application again on AWS?

Any advice and suggestions will be greatly appreciated.

Rails create has_many association models from a list of options

Posted: 20 Jan 2017 11:24 PM PST

I have options for timeslots that a user should be able to choose from:

[    { day_of_week: 'Thursday', time_of_day: '7 am' },    { day_of_week: 'Thursday', time_of_day: '8 am' },    { day_of_week: 'Thursday', time_of_day: '9 am' },    { day_of_week: 'Friday', time_of_day: '7 am' },    { day_of_week: 'Friday', time_of_day: '8 am' },    { day_of_week: 'Friday', time_of_day: '9 am' },    { day_of_week: 'Friday', time_of_day: '10 am' },    { day_of_week: 'Saturday', time_of_day: '8 am' },    { day_of_week: 'Saturday', time_of_day: '9 am' },    { day_of_week: 'Saturday', time_of_day: '10 am' }  ]  

User has_many :timeslots and a user should be able to select Timeslot based on the list above.

My current html:

   <%= simple_form_for(current_user, url: registration_path(:user)) do |f| %>          <% @timeslots.each do |day, values| %>            <div class="lead">              <%= day %>            </div>            <%= f.simple_fields_for :timeslots, values.sort_by { |slot| slot[:time_of_day].to_i } do |ff, something| %>              <div class="form-check">                <label class="form-check-label">                  <%= ff.input_field :selected %>                  <%= ff.object.time_of_day %>                </label>              </div>            <% end %>          <% end %>          <%= f.submit 'Update', class: 'btn btn-primary' %>        <% end %>  

I'd like to do two things: 1. Not have to prebuild timeslots in the database for a user 2. I can change the list (add or remove) and that would reflect the options available to the user to select from

Ruby on rails - Devise - Show user created content only

Posted: 20 Jan 2017 08:52 PM PST

I am creating a basic ruby on rails application similar to zapier or ifttt. Users create recipes. I'd like to ONLY display recipes created by the user.

I've used device gem for authentication.

My questions:

Do i add "if user_signed_in?" on the top of each page? Can I add above yield on application layouts? Is there a better way?

Do i nest recipes within users?

crossing borders of tables: language role

Posted: 20 Jan 2017 08:24 PM PST

I'm new to development, and have spent the last 12 hours (literally) trying to figure out this error message - I'm giving up for the night, but not before a quick cry for help to stackoverflow.

I have this form:

<h2>Select from the language options below (or, <%= button_to "Login", 'users/login', method: :get %></h2>    <%= form_for @language_role do |f| %>        <div id="input">        <h3>I want to learn:</h3><%= select_tag(:language_id, options_from_collection_for_select(Language.all, :id, :lang_name)) %>      </div>        <div>        <p><%= f.submit "Start learning" %></p>      </div>  <% end %>  

which is giving me this error message, highlighting the line @language_role = current_user.language_roles.build : "undefined method `language_roles' for nil:NilClass"

I have three tables:

  create_table "language_roles", force: :cascade do |t|      t.integer  "language_id"      t.boolean  "is_active"      t.boolean  "is_teacher"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "user_id"      t.index ["user_id"], name: "index_language_roles_on_user_id"    end      create_table "languages", force: :cascade do |t|      t.string   "lang_name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end  

The language_roles table is meant to allow a user to have many languages, as well as many roles within that language. Here are my class definitions:

class LanguageRole < ApplicationRecord    belongs_to :languages    belongs_to :users  end    class Language < ApplicationRecord    has_many :language_roles    has_many :users, :through => :language_roles  end    class User < ApplicationRecord    has_many :language_roles    has_many :languages, :through => :language_roles    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable  end  

My root path goes to 'home#index', where the user is supposed to pick a language if current_user.language_roles is empty. As such, I put this code in my home controller and language_roles controller:

class HomeController < ApplicationController        def index          @language_role = current_user.language_roles.build        end      end    class LanguageRolesController < ApplicationController      def create      @language_role = current_user.language_roles.build(language_role_params)      if @language_role.save        redirect_to root_path      else        redirect_to :back      end    end      private      def language_role_params      params.permit(:language_id)    end  end  

What in the hell is the problem?? I assume I need to instantiate the variable somehow, but I'm not sure how.

Thanks, Michael

Build method is not associating in Rails

Posted: 20 Jan 2017 06:56 PM PST

I'm still newbie in Rails, but got confused with the initialization of a HABTM association. Reading its documentation, it says

When initializing a new has_one or belongs_to association you must use the build_ prefix to build the association, rather than the association.build method that would be used for has_many or has_and_belongs_to_many associations.

So, basically, let's suppose we have two models:

class User < ApplicationRecord    has_and_belongs_to_many :organizations  end    class Organization < ApplicationRecord    has_and_belongs_to_many :users  end  

Inside organization_controller, since I'm using Devise, my create method should have something like this:

@organization = current_user.organizations.build(organization_params)  @organization.save  

However, it is not working. With byebug, I checked that for the current_user.organizations, the new organization was there, but, if I call @organization.users, there's an empty array. Looks like it's required to run current_user.save as well, is it correct? I was able to associate both models with this code:

@organization = Organization.new(organization_params)  @organization.users << current_user  @organization.save  

Tinymce default styles in Rails app

Posted: 20 Jan 2017 04:49 PM PST

I was following the tutorial on How to build a blog with Rails 5 and Bootstrap 4 - Part 5, initialized Tinymce Editor but I can't change the default font size of text in this editor. I have this code in application.js:

document.addEventListener("turbolinks:load", function() {    tinymce.remove();    tinymce.init({        selector: 'textarea#post_body',    height: 500,    plugins: [        "advlist autolink autosave link image lists charmap",        "wordcount media code",        "table contextmenu textcolor paste"      ],    toolbar1: "undo redo | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",    toolbar2: "cut copy paste | bullist numlist | outdent indent blockquote | link image media | forecolor | table | subscript superscript | charmap | code",    menubar: false,    content_css : "/assets/application.css"  });  

})

In application.css:

 *= require_tree .   *= require_self  @import "bootstrap-sprockets";  @import "bootstrap";  @import "font-awesome";  

And there are other two files with styles (custom.scss and posts.scss). I tried putting in custom.scss:

body.mce-content-body {      font-size: 16px;      background-color: gray;}    body.mce-content-body p {      font-size: 16px;}    [data-mce-style] {      font-size: 16px;}  

I also tried the following:

-clearing browser cache several times

-copying custom.scss and linking to the new file in content_css as per this suggestion

-using content_style: ".mce-content-body p { font-size: 16px;}"

The file is being added to the head of the iframe and its background color is changing, but the styles for paragraphs are always being overwritten by their default inline styles :<p style="box-sizing: border-box; margin: 0px 0px 1.1em; padding: 0px; border: 0px; font-size: 19.35px; line-height: 32.895px; font-family: Lato, sans-serif; color: #444444;" data-mce-style="box-sizing: border-box; margin: 0px 0px 1.1em; padding: 0px; border: 0px; font-size: 19.35px; line-height: 32.895px; font-family: Lato, sans-serif; color: #444444;">...</p>

Another problem is that even if I change the background-color while editing post, the default styles are back when I submit the form and show all blog posts :(

Any ideas, please?

ODD ISSUE: Heroku app works great on few computers but not the others. Could running "heroku restart" cause the issue?

Posted: 20 Jan 2017 05:59 PM PST

I am running into a very odd issue and coming up short with identifying the issue. I don't even know if it is a front-end, server or heroku issue. Please help me out.

I am managing a Rails App (with React front-end), hosting on Heroku. It is a workforce management and dispatching app. It has been working fine the whole time, until earlier today, when I made a huge feature deployment. The deployment was successful, and I tested the old & new features fine on all of our testing computers. After deployment, I ran heroku run rake db:migrate and heroku restart. During this time, we have customers using the web app on their local computers, in different time zones.

Few minutes later, I got a call from multiple customers, each mentioning that at least one of their dispatching features is not working, all of which were older features/components that shouldnt have been affected. Some say they cant see their workers. One say they cant see jobs on a particular day. Some say they cant see jobs on another. When I check the heroku logs, I see no errors whatsoever. Routes are called fine and things are passed correctly back to the front-end. When logging into their app with master credentials, we also were unable to replicate ANY of these issues on ANY of our computers. All of our customers uses Chrome, but checking on both Mac and Windows reveal no issues from our ends. Yet, the issue still remains.

We then decided to revert our deployment and deployed an earlier version. Same thing. Everything works on ours, and customers continue to say these features/components just appear...blank. We tried heroku run rake tmp:clear to clear heroku cache, still no luck.

Thank you. Any comments will be highly appreciated.

Strong Params: params.permit returns Unpermitted parameters despite whitelist

Posted: 20 Jan 2017 06:54 PM PST

UsersProfileController has strong params that looks like so:

    def user_profile_params        params.permit(:age, :relations)        # yes, I am not requiring user_profile. Just permitting attributes I need.       end  

The create action builds UserProfile through a parent (has-one and belongs-to association)

    def create        parent = Parent.create_guest        parent.build_user_profile(user_profile_params)        if parent.save           # do something         else           # handle error        end      end  

Calling params in UserProfiles returns:

    <ActionController::Parameters         {"age"=>"23",          "relations"=>"3",          "subdomain"=>"api",          "format"=>:json,          "controller"=>"api/v1/user_profiles",          "action"=>"create"}        permitted: false>  

Calling user_profile_params, returns this:

    user_profile_params:        Unpermitted parameters: subdomain, format        <ActionController::Parameters          {"age"=>"23",          "relations"=>"3", }         permitted: true>  

When a post request comes in, I expect to be able to create user_profile using the whitelisted params in user_profile_params. Instead, the create action in UserProfiles fails with error: Unpermitted parameters: subdomain, format.

This isn't what I expected. I expected user_profile_params to only include the permitted values and ignore all others.

I could add :format and :subdomain to list of permitted attributes but something feels a bit off about that.

Can someone explain what is going on/what I am missing?