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!

No comments:

Post a Comment