Wednesday, May 25, 2016

In Rails, extended Integer class written in lib folder is not getting loaded with the eager loading of lib | Fixed issues

In Rails, extended Integer class written in lib folder is not getting loaded with the eager loading of lib | Fixed issues


In Rails, extended Integer class written in lib folder is not getting loaded with the eager loading of lib

Posted: 25 May 2016 07:23 AM PDT

I have created a file integer.rb in lib folder and that contains the following peace of code

class Integer    def digits      self.abs.to_s.size    end  end  

I am loading the lib folder in application.rb file with this line

config.eager_load_paths += %W(#{config.root}/lib)  

but it doesn't seem to be loading the lib/integer.rb file, but if I explicitly write
require "#{config.root}/lib/integer"
then the digits method I wrote gets available for the usage.
Why do I have to explicitly load the file when I am loading the whole lib folder already?

Rails version I use is 4.0.0

User Grape Entity with Arrays

Posted: 25 May 2016 07:18 AM PDT

I was wondering whether Grape Entity would work for rendering arrays of hashes, I thought I remebered it worked but somehow I cannot get it to work right now, am I doing some obvious mistake? Here's my Entity:

class V1::Entities::Searchresult < Grape::Entity     expose :_type, as: :type     expose :_id, as: :id     expose :_score, as: :score     expose :highlight  end  

In my API I call the rendering like this:

present result['hits']['hits'], with: V1::Entities::Searchresult, :params => params  

The 'result['hits']['hits']' is filled with 10 hashes that contain the data. The data is present. However when I look at the result I get:

[    {      "type": null,      "id": null,      "score": null,      "highlight": null    },    {      "type": null,      "id": null,      "score": null,      "highlight": null    },    ......  

Am I doing something wrong, or is this simply not possible. I can't seem to dig up any documentation on the array toppic.

Cheers

Tom

How do I save two objects at once in a Rails form?

Posted: 25 May 2016 07:06 AM PDT

I'm using Rails 4.2.3. How do I save two objects with one form? I have these two models …

class MyObject < ActiveRecord::Base    belongs_to :user    has_many :my_object_times    attr_accessor :hour, :minute, :second      accepts_nested_attributes_for :my_object_times  end  

and

class MyObjectTime < ActiveRecord::Base    belongs_to :my_object  end  

I want to submit a single form that creates both a MyObject and a MyObjectTime object. So I created my form

<%= form_for @my_object do |f| %>    <div class="field">      <%= f.label :name %><br>      <%= f.text_field :name %>    </div>    <div class="field">      <%= f.label "Time" %>      <%= select_tag('my_object[hour]', options_for_select((0..12).to_a), {:prompt => 'Select Hour'} ) %> hrs      <%= select_tag('my_object[minute]', options_for_select((0..60).to_a), {:prompt => 'Select Minutes'} ) %> min      <%= select_tag('my_object[second]', options_for_select((0..60).to_a), {:prompt => 'Select Seconds'} ) %> sec      <%= f.fields_for :my_object_time do |mot| %>        <%= mot.number_field :time_in_ms %>      <% end %>    </div>      <div class="actions">      <%= button_to "Save", { :action => "create" }, :method => :post, :class => 'button' %>    </div>  <% end %>  

and here's my controller …

  def create      @my_object = MyObject.new(my_object_params)      @current_user = User.find(session["user_id"])      @my_object.user = @current_user      if @my_object.save        respond_to do |format|          format.html { redirect_to controller: "users", action: "index", notice: 'Saved successfully.' }        end      else        format.html { render action: "index" }      end    end  

However, only the MyObject object is getting saved and not a corresponding MyObjectTime. Is there a way I can get both to get created at once? I don't want a situation where one gets created and the second does not. I want either both to get created or nothing to happen at all and an error returned.

Handling post request error properly

Posted: 25 May 2016 07:02 AM PDT

My rails controller index method reads post requests. However, when the application first starts, the post request does not exist and it throws a

undefined method `[]' for nil:NilClass

To account for this condition, I have the following block of code. Basically, if reading the post request generates an error it sets a value manually.

begin      @business = params[:business_name]  rescue      @business = ["Nestle"]  end  

I have a feeling this is a poor approach to solve this problem. What would be a better way?

In Rubymine, Rails failes to load 'uglifier' gem

Posted: 25 May 2016 07:00 AM PDT

I have an issue while running Rails from Rubymine where it fails to load the uglifier gem with the stack below. Note that Node.js is installed on my Windows 7 computer.

From cmd.exe, 'rails s' works well : the web application starts.

From RubyMine run button, default configuration, I get the error :

"C:\Program Files (x86)\JetBrains\RubyMine 8.0.2\bin\runnerw.exe" C:\tools\languages\RailsInstaller\Ruby2.2.0\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/projects/perso/exercises/bin/rails server -b 127.0.0.1 -p 3000 -e development  C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'uglifier'. (Bundler::GemRequireError)      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'      from C:/projects/perso/exercises/config/application.rb:7:in `<top (required)>'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `require'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `block in server'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'      from C:/tools/languages/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'      from C:/projects/perso/exercises/bin/rails:4:in `require'      from C:/projects/perso/exercises/bin/rails:4:in `<top (required)>'      from -e:1:in `load'      from -e:1:in `<main>'  Process finished with exit code 1  

I get the same error from RubyMine terminal.

Here's some information on my environment from (same output from cmd.exe and RubyMine) :

>rails --version  Rails 4.2.6  >node --version  v0.10.22  >ruby --version  ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]  

Ruby was installed using Rails Installer on a Windows 7 computer. Node.js is installed too, using official installer. RubyMine 8.0.4 (ultimate, not sure if there's a community version too)

I suspect an environment problem inside RubyMine in which rails/bundler/gem/? can't "see" Node.js, where cmd.exe can.

I think the error started when I tryed to start RubyMine debug mode.

Any idea on how to solve the issue ?

Thanks

Rails Sidekiq job doesn't seem to be parsing

Posted: 25 May 2016 06:57 AM PDT

I'm trying to mimic what a previous developer did to parse an XML file in my Rails app and am stuck. From what I can tell, my job completes, but nothing is being posted as it should be, so I'm guessing my parsing file is incorrect (however, it works fine when testing with the raw file on my localhost). So, where am I going wrong here?

Sidekiq log output (just to confirm job is happening and not showing any errors in processing):

2016-05-25T13:51:04.499Z 8977 TID-oxs3s9lng ParseTestData JID-2a01971539c887cac3bf3374:1 INFO: start  2016-05-25T13:51:04.781Z 8977 TID-oxs3s9l3g GenerateNotifications JID-2a01971539c887cac3bf3374:2 INFO: start  2016-05-25T13:51:04.797Z 8977 TID-oxs3s9lng ParseTestData JID-2a01971539c887cac3bf3374:1 INFO: done: 0.297 sec  2016-05-25T13:51:04.824Z 8977 TID-oxs3s9l3g GenerateNotifications JID-2a01971539c887cac3bf3374:2 INFO: done: 0.043 sec  

My Sidekiq job file, which iterates through the compressed files that get submitted through my API. The file in question that I'm working on is nmap_poodle_scan.xml:

class ParseTestData    include Sidekiq::Worker      # Order matters. Parse network hosts first to ensure we uniquely identify network hosts by their mac address.    PARSERS = {      "network_hosts.xml" => Parsers::NetworkHostParser,      "nmap_tcp_service_scan.xml" => Parsers::TcpServiceScanParser,      "nmap_shellshock_scan.xml" => Parsers::ShellshockScanParser,      "hydra.out" => Parsers::HydraParser,      "events.log" => Parsers::EventParser,      "nmap_poodle_scan.xml" => Parsers::PoodleScanParser    }      def perform(test_id)      test = Test.find(test_id)        gzip = if Rails.env.development?        Zlib::GzipReader.open(test.data.path)      else        file = Net::HTTP.get(URI.parse(test.data.url))        Zlib::GzipReader.new(StringIO.new(file))      end        # Collect entries from tarball      entries = {}      tar_extract = Gem::Package::TarReader.new(gzip)      tar_extract.rewind      tar_extract.each do |entry|        entries[File.basename(entry.full_name)] = entry.read      end        # Preserve parse order by using the parser hash to initiate parser executions.      PARSERS.each_pair do |filename, parser|        next unless entry = entries[filename]        parser.run!(test, entry)      end    end  end  

Which grabs nmap_poodle_scan.xml:

<host starttime="1464180941" endtime="1464180941"><status state="up" reason="arp-response" reason_ttl="0"/>  <address addr="10.10.10.1" addrtype="ipv4"/>  <address addr="4C:E6:76:3F:2F:77" addrtype="mac" vendor="Buffalo.inc"/>  <hostnames>  <hostname name="DD-WRT" type="PTR"/>  </hostnames>  Nmap scan report for DD-WRT (10.10.10.1)  <ports><extraports state="closed" count="996">  <extrareasons reason="resets" count="996"/>  </extraports>  <table key="CVE-2014-3566">  <elem key="title">SSL POODLE information leak</elem>  <elem key="state">VULNERABLE</elem>  <table key="ids">  <elem>OSVDB:113251</elem>  <elem>CVE:CVE-2014-3566</elem>  </table>  <table key="description">  <elem>    The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and&#xa;    other products, uses nondeterministic CBC padding, which makes it easier&#xa;    for man-in-the-middle attackers to obtain cleartext data via a&#xa;    padding-oracle attack, aka the &quot;POODLE&quot; issue.</elem>  </table>  <table key="dates">  <table key="disclosure">  <elem key="year">2014</elem>  <elem key="month">10</elem>  <elem key="day">14</elem>  </table>  </table>  <elem key="disclosure">2014-10-14</elem>  <table key="check_results">  <elem>TLS_RSA_WITH_3DES_EDE_CBC_SHA</elem>  </table>  <table key="refs">  <elem>https://www.imperialviolet.org/2014/10/14/poodle.html</elem>  <elem>http://osvdb.org/113251</elem>  <elem>https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566</elem>  <elem>https://www.openssl.org/~bodo/ssl-poodle.pdf</elem>  </table>  </table>  </script></port>  </ports>  <times srtt="4665" rttvar="556" to="100000"/>  </host>  

Which should submit to PoodleScanParser:

module Parsers    class PoodleScanParser < NmapScanParser      def self.run!(test, content)        super(test, content, "//host[.//elem/@key='state']") do |host, network_host_test|          result =  host.at_xpath("//ports//elem[@key='state']").content if result == "VULNERABLE"          if result            IssueFinder.match(cve_id: "CVE-2014-3566").each do |issue|              Result.generate!(network_host_test.id, issue.id)            end          end        end      end    end  end  

Which inherits from NmapScanParser (This file is parser is confirmed to work fine, so I know it's not the issue):

module Parsers    class NmapScanParser        def self.run!(test, content, xpath)        document = Nokogiri::XML(content)        document.remove_namespaces!          document.xpath(xpath).each do |host|          ip_address = host.at_xpath("address[@addrtype='ipv4']").at_xpath("@addr").value          vendor = host.at_xpath("address[@addrtype='mac']").at_xpath("@vendor").value rescue "Unknown"          hostname = host.at_xpath("hostnames/hostname").at_xpath("@name").value rescue "Hostname Unknown"          os = host.at_xpath("os/osmatch").at_xpath("@name").value rescue "Unknown"          os_vendor = host.at_xpath("os/osmatch/osclass").at_xpath("@vendor").value rescue "Unknown"            network_host_test = NetworkHostTest.generate!(test, ip_address: ip_address, hostname: hostname, vendor: vendor, os: os, os_vendor: os_vendor)            # If we didn't find a network host, that's because our network_hosts file didn't have this entry.          next unless network_host_test            yield(host, network_host_test)        end      end      end  end  

I've confirmed the parser works on my localhost with the same raw output as above using a plain ruby file, and running ruby poodle_parser.rb:

require 'nokogiri'    document = Nokogiri::XML(File.open("poodle_results.xml"))  document.remove_namespaces!    document.xpath("//host[.//elem/@key='state']").each do |host|    ip_address = host.at_xpath("address[@addrtype='ipv4']").at_xpath("@addr").value    result =  host.at_xpath("//ports//elem[@key='state']").content    puts "#{ip_address} #{result}"  end  

Which outputs what I would expect in terminal:

10.10.10.1 VULNERABLE  

So, in the end, I expect a Result to be generated, but it's not. I'm not seeing any errors in the Rails log on my localhost, nor am I seeing anything indicating an error in the Sidekiq logs either!

(JavaScript) (Ruby on rails) Change Map Variables from another view

Posted: 25 May 2016 06:54 AM PDT

Hello i have a google map like this:

<script type="text/javascript">      var map;      var elements_coords = <%= @map_flumes_hour.to_json.html_safe %>;      function initMap() {      map = new google.maps.Map(document.getElementById('map'), {          center: {            lat: 36.46,            lng: -5.0          },          zoom: 10,          mapTypeId: google.maps.MapTypeId.HYBRID      });  </script>  

I want to add Markers (google.maps.Marker) and Lines (google.maps.Polyline) from another view, because i need to refresh the color of markers and lines every 5 seconds but not the entire map, i try to add the lines of Markers and Lines in the another view but dont change the color. Sorry for my English. Thanks in advance

how to: rails base validation view

Posted: 25 May 2016 06:59 AM PDT

As mentioned here

You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since errors[:base] is an array, you can simply add a string to it and it will be used as an error message.

class Person < ActiveRecord::Base    def a_method_used_for_validation_purposes      errors[:base] << "This person is invalid because ..."    end  

My validation actually works but it does not automatically display an error message. Here is what I've got:

  def free_plan_can_only_have_one_room      if self.new_record? && (tenant.rooms.count > 0) && (tenant.plan == 'free')        errors.add(:base, "Free plans cannot have more than 1 room")      end    end  

Any Ideas how to create the view for the error?

My view:

= simple_form_for @room, :html => { :class => 'form-horizontal' } do |f|    = f.error_notification    = f.input :name    = f.association :office    = f.button :submit, :class => 'btn-primary'    = link_to 'Back to all rooms', rooms_path, :class => 'btn btn-default'  

Nokugiri web scrape issue

Posted: 25 May 2016 07:14 AM PDT

Seeming as i didn't ask this very well the first time. Heres another go.

I'm trying to follow this tutorial here: http://railscasts.com/episodes/190-screen-scraping-with-nokogiri

I'm currently also trying to scrape the price from this website link here: http://www.ticketmaster.co.uk/derren-brown-miracle-glasgow-04-07-2016/event/370050789149169E?artistid=1408737&majorcatid=10002&minorcatid=53&tpab=-1

What i'm wanting to achieve is to have all three of these ticket (name and price hopefully as much information about the tickets/prices as possible) and use them in my web application.

I can't show you the result, Its stupidly big in size, But i can tell you that i don't hit the second byebug, Heres my code.

  url = "http://www.ticketmaster.co.uk/derren-brown-miracle-glasgow-04-07-2016/event/370050789149169E?artistid=1408737&majorcatid=10002&minorcatid=53&tpab=-1"      doc = Nokogiri::HTML(open(url))      byebug      doc.css(".item").each do |item|        title = item.at_css(".fru").text        byebug      end  

Unfortunately to help you'll ideally have to try this yourself to see the horrible page size! haha!

Edit, Ok baring in mind my screen is 27 inches, The text FILLS the screen

Heres an image of what i got in from the first image.

huge image of response

Further to this i believe that this image here is all i need? its just getting it out.

what i might need!

Thanks Sam

how do i ensure persistence in rails?

Posted: 25 May 2016 06:32 AM PDT

hi guys, this is my signup code

<%= render 'shared/errors',obj:@user %>     <div class="row">     <div class="col-xs-12">       <%= form_for(@user, :html => {class: "form-horizontal", role: "form"}) do |f| %>        <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :username %>        </div>        <div class="col-sm-8">          <%= f.text_field :username, class: "form-control", placeholder: "Enter username", autofocus: true %>        </div>      </div>        <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :email %>        </div>        <div class="col-sm-8 ">          <%= f.email_field :email, class: "form-control", placeholder: "Enter email", autofocus: true %>        </div>      </div>        <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :password %>        </div>        <div class="col-sm-8">          <%= f.password_field :password,class: "form-control",placeholder: "Enter password" %>        </div>      </div>        <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :password_confirmation, 'Confirm' %>        </div>        <div class="col-sm-8">          <%= f.password_field :password_confirmation,class: "form-control", autofocus:true %>        </div>      </div>         <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :phone %>        </div>        <div class="col-sm-8 ">          <%= f.text_field :phone, class: "form-control", placeholder: "Phone number", autofocus: true %>        </div>      </div>        <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :city %>        </div>        <div class="col-sm-8 ">          <%= f.text_field :city, class: "form-control", placeholder: "Enter city", autofocus: true %>        </div>      </div>        <div class="form-group">        <div class="control-label col-sm-2">          <%= f.label :birthday %>        </div>        <div class="col-sm-8 ">          <%= f.date_field :birthday, class: "form-control", placeholder: "Enter birthday", autofocus: true %>        </div>      </div>        <div class="form-group">        <div class="col-sm-1 col-xs-offset-2">          <%= f.radio_button :sex, "female" %>        </div>        <div class="control-label col-sm-1">          <%= f.label :sex, "Female",  autofocus: true %>        </div>          <div class="col-sm-1">          <%= f.radio_button :sex, "male" %>        </div>        <div class="control-label col-sm-1">          <%= f.label :sex, "Male",  autofocus: true %>        </div>      </div>        <div class="form-group">         <div class="col-sm-offset-2 col-sm-10">           <%= f.submit(@user.new_record? ? "Sign up" : "Update account", class: "btn btn-primary btn-lg")%>         </div>      </div>     <% end %>     <div class="col-xs-4 col-xs-offset-4">     [<%= link_to "Cancel request and return to articles listing", articles_path %>]   </div>       </div>   </div>  

this is my migration code

class CreateUsers < ActiveRecord::Migration    def change      create_table :users do |t|        t.string :username        t.string :email        t.string :phone        t.string :city        t.date   :birthday        t.string :sex          t.timestamps      end    end  end  

this is my users show code

<br><h3 align="center">Welcome to <%= @user.username %>'s page</h3>  <div class="row">      <div class="col-md-4 col-md-offset-4" align="center">          <%= gravatar_for @user, size: 150 %>      </div>  </div>  <br><div class="row align="center" ">      Sex: <%= @user.sex %><br>      Phone: <%= @user.phone %><br>      City: <%= @user.city %><br>      Birthday: <%= @user.birthday %>       <h4><%= @user.username %>'s articles</h4>  </div>  <div align="center">      <%= will_paginate @user_articles %>  </div>  <%= render 'articles/article', obj: @user_articles %>  <div align="center">      <%= will_paginate @user_articles %>  </div>  

but the sex, phone city and birthday are not showing in the users show page. How do i save this data to the database so that it will display?

Can this ldap filter join be done in one statement?

Posted: 25 May 2016 05:59 AM PDT

I am pulling employee names from active directory for a rails app. It is working overall except that there are some 'non real people' entries that have a cn=people such as 'conference room'. I need to eliminate those. I can do that with an iterative filter join but that seems horribly inefficient and kludgy.

What I have now is

    filter1 = (Net::LDAP::Filter.ge( "sn", "a"))      filter2 = Net::LDAP::Filter.eq( "givenName", "c*" )      filter3 = Net::LDAP::Filter.ne("samaccountname", "croom" )      treebase = "dc=xxxxxx,dc=com"        joined_filter = Net::LDAP::Filter.join(filter1, filter2)      joined_filter = Net::LDAP::Filter.join(joined_filter, filter3)        @temp_search = ldap.search( :base => treebase, :filter => joined_filter )  

that gives me all employees with a surname greater than or equal to 'a' (I know that needs to be tweaked) and a given name starting with 'c'. Filter3 excludes the conference room "croom". It seems there should be some way to pass an array into a filter. If I try to pass all three filters to a join, I get a 'wrong number of arguments'

Is there a way to pass multiple exclusions such as 'croom' 'croom2' 'breakroom' etc?

Foundation 6, Reveal modal not white

Posted: 25 May 2016 06:22 AM PDT

im having some issue with the Foundation reveal modals. When the modal open,its red not white and i cant figure out how to change that there is my code.

#exampleModal1.reveal{"data-reveal" => ""}    %h1 Awesome. I Have It.    %p.lead Your couch. It is mine.    %p I'm a cool paragraph that lives inside of an even cooler modal. Wins!    %button.close-button{"aria-label" => "Close modal", "data-close" => "", :type => "button"}      %span{"aria-hidden" => "true"} ×  

Rails saving two different model instances as a singular transaction

Posted: 25 May 2016 06:21 AM PDT

I am writing a service object for a sign up form that records data for a User and a Company model (FYI, I flat out refuse to use nested_attributes).

A User cannot exist without the presence of a Company (belongs_to).

IF the company succeeds and the user does not succeed in saving, how do I roll back the creation of the company?

I have tests copied below to demonstrate the point..

  context 'when both are valid?' do      subject { -> { sign_up_object.save } }      it { should change(Company, :count).by(1) }      it { should change(sign_up_object, :company).to be_a Company }      it { should change(User, :count).by(1) }      it { should change(sign_up_object, :user).to be_a User }    end    context 'when COMPANY is invalid' do      subject { -> { sign_up_object.save } }      before { allow_any_instance_of(Company).to receive(:save!).and_return false }      it { should change(User, :count).by(0) }      it { should change(Company, :count).by(0) }    end    context 'when USER is invalid' do      before { allow_any_instance_of(User).to receive(:save!).and_return false }      subject { -> { sign_up_object.save } }      it { should change(User, :count).by(0) }      it { should change(Company, :count).by(0) }  ->>>> this one fails!!!    end  

The code I have at the moment looks something like this

class SignUp      ......      def save_resources      ActiveRecord::Base.transaction do        save_company        save_user      end    end      def save_company      company = new_company      self.company = company if company.save!    end      def save_user      user = new_user      self.user = user if user.save!    end  end  

I'm sure the ActiveRecord::Base.transaction block isn't actually doing anything, as my tests show the user spec as the only one as failing, as a company count is going up by 1.

After sign in path devise, does not work in production

Posted: 25 May 2016 05:56 AM PDT

I have the following code in application_controller.rb

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :exception       def after_sign_in_path_for(resource)      main_app.home_path    end      def after_sign_out_path_for(resource)      main_app.home_path    end      protected      def after_update_path_for(resource)      main_app.home_path    end    end  

This works fine in development environment. But the redirection to home_path does not happen in production. What may be the reason for it? Can any one please help me out.

There is no error I got here are the logs DEBUG [604263e2] I, [2016-05-25T12:38:33.626818 #18910] INFO -- : Started GET "/logout" for 106.51.242.28 at 2016-05-25 12:38:33 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:33.629504 #18910] INFO -- : Processing by Spree::UserSessionsController#destroy as HTML DEBUG [604263e2] D, [2016-05-25T12:38:33.631652 #18910] DEBUG -- : Spree::User Load (0.8ms) SELECT "spree_users".* FROM "spree_users" WHERE "spree_users"."deleted_at" IS NULL AND "spree_users"."id" = $1 ORDER BY "spree_users"."id" ASC LIMIT 1 [["id", 3]] DEBUG [604263e2] D, [2016-05-25T12:38:33.634317 #18910] DEBUG -- : Spree::Store Load (1.0ms) SELECT "spree_stores".* FROM "spree_stores" WHERE (url like '%shijokes-prod-elb-1019143626.us-east-1.elb.amazonaws.com%') ORDER BY "spree_stores"."id" ASC LIMIT 1 DEBUG [604263e2] D, [2016-05-25T12:38:33.635818 #18910] DEBUG -- : Spree::Order Load (0.7ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NULL AND "spree_orders"."currency" = $1 AND "spree_orders"."guest_token" = $2 AND "spree_orders"."store_id" = $3 AND "spree_orders"."user_id" = $4 LIMIT 1 [["currency", "USD"], ["guest_token", "3MHdkOcp_gtA1p6FkJ60xQ1464179721094"], ["store_id", 1], ["user_id", 3]] DEBUG [604263e2] D, [2016-05-25T12:38:33.637628 #18910] DEBUG -- : Spree::Order Load (0.8ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."user_id" = $1 AND "spree_orders"."completed_at" IS NULL ORDER BY created_at DESC LIMIT 1 [["user_id", 3]] DEBUG [604263e2] D, [2016-05-25T12:38:33.638932 #18910] DEBUG -- : (0.6ms) BEGIN DEBUG [604263e2] D, [2016-05-25T12:38:33.640521 #18910] DEBUG -- : (0.7ms) COMMIT DEBUG [604263e2] I, [2016-05-25T12:38:33.644286 #18910] INFO -- : Redirected to http://shijokes-prod-elb-1019143626.us-east-1.elb.amazonaws.com/home DEBUG [604263e2] I, [2016-05-25T12:38:33.644478 #18910] INFO -- : Completed 302 Found in 15ms (ActiveRecord: 4.6ms) DEBUG [604263e2] I, [2016-05-25T12:38:34.022949 #18907] INFO -- : Started GET "/home" for 106.51.242.28 at 2016-05-25 12:38:34 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:34.025495 #18907] INFO -- : Processing by HomeController#index as HTML DEBUG [604263e2] I, [2016-05-25T12:38:34.028272 #18907] INFO -- : Rendered home/index.html.erb within layouts/application (1.8ms) DEBUG [604263e2] I, [2016-05-25T12:38:34.043845 #18907] INFO -- : Rendered partials/_header.html.erb (14.9ms) DEBUG [604263e2] I, [2016-05-25T12:38:34.045127 #18907] INFO -- : Rendered partials/_footer_partial.html.erb (1.0ms) DEBUG [604263e2] I, [2016-05-25T12:38:34.045364 #18907] INFO -- : Completed 200 OK in 20ms (Views: 19.2ms | ActiveRecord: 0.0ms) DEBUG [604263e2] I, [2016-05-25T12:38:37.176396 #18910] INFO -- : Started GET "/order_details" for 106.51.242.28 at 2016-05-25 12:38:37 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:37.178846 #18910] INFO -- : Processing by OrderDetailsController#index as HTML DEBUG [604263e2] I, [2016-05-25T12:38:37.179935 #18910] INFO -- : Redirected to http://shijokes-prod-elb-1019143626.us-east-1.elb.amazonaws.com/please_login DEBUG [604263e2] I, [2016-05-25T12:38:37.180052 #18910] INFO -- : Filter chain halted as :check_login rendered or redirected DEBUG [604263e2] I, [2016-05-25T12:38:37.180210 #18910] INFO -- : Completed 302 Found in 1ms (ActiveRecord: 0.0ms) DEBUG [604263e2] I, [2016-05-25T12:38:37.427200 #18907] INFO -- : Started GET "/please_login" for 106.51.242.28 at 2016-05-25 12:38:37 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:37.429700 #18907] INFO -- : Processing by OrderLoginController#login as HTML DEBUG [604263e2] I, [2016-05-25T12:38:37.430766 #18907] INFO -- : Rendered order_login/login.html.erb within layouts/application (0.1ms) DEBUG [604263e2] I, [2016-05-25T12:38:37.446095 #18907] INFO -- : Rendered partials/_header.html.erb (14.7ms) DEBUG [604263e2] I, [2016-05-25T12:38:37.447394 #18907] INFO -- : Rendered partials/_footer_partial.html.erb (1.1ms) DEBUG [604263e2] I, [2016-05-25T12:38:37.447667 #18907] INFO -- : Completed 200 OK in 18ms (Views: 17.3ms | ActiveRecord: 0.0ms) DEBUG [604263e2] I, [2016-05-25T12:38:42.601305 #18910] INFO -- : Started POST "/login" for 106.51.242.28 at 2016-05-25 12:38:42 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:42.603837 #18910] INFO -- : Processing by Spree::UserSessionsController#create as HTML DEBUG [604263e2] I, [2016-05-25T12:38:42.603952 #18910] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"/2OrcNWTXSLxbEHYvLgnlvUPqGEHipfSnMXg80A+eqTOWbhzF3bW2BTDGIkago2CIAJSsOdSS9jY7pjnSl3Ngg==", "spree_user"=>{"email"=>"gvpmahesh@gmail.com", "password"=>"[FILTERED]"}, "commit"=>"login"} DEBUG [604263e2] D, [2016-05-25T12:38:42.606220 #18910] DEBUG -- : Spree::Order Exists (0.8ms) SELECT 1 AS one FROM "spree_orders" WHERE "spree_orders"."guest_token" = $1 LIMIT 1 [["guest_token", "UzHBGWJYwxWIExtP2VoTnQ1464179922604"]] DEBUG [604263e2] D, [2016-05-25T12:38:42.608319 #18910] DEBUG -- : Spree::User Load (0.9ms) SELECT "spree_users".* FROM "spree_users" WHERE "spree_users"."deleted_at" IS NULL AND "spree_users"."email" = $1 ORDER BY "spree_users"."id" ASC LIMIT 1 [["email", "gvpmahesh@gmail.com"]] DEBUG [604263e2] D, [2016-05-25T12:38:42.610534 #18910] DEBUG -- : Spree::Order Load (0.8ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."email" = $1 AND "spree_orders"."guest_token" = $2 AND "spree_orders"."user_id" IS NULL [["email", "gvpmahesh@gmail.com"], ["guest_token", "UzHBGWJYwxWIExtP2VoTnQ1464179922604"]] DEBUG [604263e2] D, [2016-05-25T12:38:42.612179 #18910] DEBUG -- : (0.6ms) BEGIN DEBUG [604263e2] D, [2016-05-25T12:38:42.614098 #18910] DEBUG -- : SQL (0.9ms) UPDATE "spree_users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "spree_users"."id" = $5 [["last_sign_in_at", "2016-05-25 12:35:21.102703"], ["current_sign_in_at", "2016-05-25 12:38:42.610959"], ["sign_in_count", 17], ["updated_at", "2016-05-25 12:38:42.612459"], ["id", 3]] DEBUG [604263e2] D, [2016-05-25T12:38:42.616005 #18910] DEBUG -- : (1.4ms) COMMIT DEBUG [604263e2] D, [2016-05-25T12:38:42.617836 #18910] DEBUG -- : Spree::Store Load (0.9ms) SELECT "spree_stores".* FROM "spree_stores" WHERE (url like '%shijokes-prod-elb-1019143626.us-east-1.elb.amazonaws.com%') ORDER BY "spree_stores"."id" ASC LIMIT 1 DEBUG [604263e2] D, [2016-05-25T12:38:42.619286 #18910] DEBUG -- : Spree::Order Load (0.7ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."completed_at" IS NULL AND "spree_orders"."currency" = $1 AND "spree_orders"."guest_token" = $2 AND "spree_orders"."store_id" = $3 AND "spree_orders"."user_id" = $4 LIMIT 1 [["currency", "USD"], ["guest_token", "UzHBGWJYwxWIExtP2VoTnQ1464179922604"], ["store_id", 1], ["user_id", 3]] DEBUG [604263e2] D, [2016-05-25T12:38:42.621043 #18910] DEBUG -- : Spree::Order Load (0.8ms) SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."user_id" = $1 AND "spree_orders"."completed_at" IS NULL ORDER BY created_at DESC LIMIT 1 [["user_id", 3]] DEBUG [604263e2] I, [2016-05-25T12:38:42.622194 #18910] INFO -- : Redirected to http://shijokes-prod-elb-1019143626.us-east-1.elb.amazonaws.com/orders/populate?controller=home DEBUG [604263e2] I, [2016-05-25T12:38:42.622363 #18910] INFO -- : Completed 302 Found in 18ms (ActiveRecord: 7.8ms) DEBUG [604263e2] I, [2016-05-25T12:38:42.864497 #18907] INFO -- : Started GET "/orders/populate?controller=home" for 106.51.242.28 at 2016-05-25 12:38:42 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:43.105024 #18907] INFO -- : Started GET "/please_login" for 106.51.242.28 at 2016-05-25 12:38:43 +0000 DEBUG [604263e2] I, [2016-05-25T12:38:43.107563 #18907] INFO -- : Processing by OrderLoginController#login as HTML DEBUG [604263e2] I, [2016-05-25T12:38:43.108655 #18907] INFO -- : Rendered order_login/login.html.erb within layouts/application (0.1ms) DEBUG [604263e2] D, [2016-05-25T12:38:43.124942 #18907] DEBUG -- : Spree::User Load (1.0ms) SELECT "spree_users".* FROM "spree_users" WHERE "spree_users"."deleted_at" IS NULL AND "spree_users"."id" = $1 ORDER BY "spree_users"."id" ASC LIMIT 1 [["id", 3]] DEBUG [604263e2] I, [2016-05-25T12:38:43.126375 #18907] INFO -- : Rendered partials/_header.html.erb (17.1ms) DEBUG [604263e2] I, [2016-05-25T12:38:43.127700 #18907] INFO -- : Rendered partials/_footer_partial.html.erb (1.1ms) DEBUG [604263e2] I, [2016-05-25T12:38:43.127955 #18907] INFO -- : Completed 200 OK in 20ms (Views: 18.7ms | ActiveRecord: 1.0ms)

Rails + Heroku + Bonsai still try to connect 9200

Posted: 25 May 2016 06:14 AM PDT

I attached a screenshot(error screen shot ) which indicates the error.

Faraday::ConnectionFailed in Devise::SessionsController#create

Connection refused - connect(2) for "localhost" port 9200

I am using bonsai with ruby on rails and deployed to heroku. But it still tries to connect to local 9200.

I have initialiser file as below.

config/initializers/bonsai.rb

require 'elasticsearch/model'    if ENV['BONSAI_URL']    Elasticsearch::Model.client = Elasticsearch::Client.new({url: ENV['BONSAI_URL'], logs: true})  end  

Could anyone please help me on this?

QR code link to a modal

Posted: 25 May 2016 06:47 AM PDT

Is it possible to create a QR code that redirects the user to a modal in a specific page? As in, you send him to the page X but already trigger click <%= link_to "modaltoshow %> , and the user sees the modal immediately after scanning.

Thanks

How to access Main Rails App controllers variable inside the Rails Enigne application

Posted: 25 May 2016 04:57 AM PDT

I have created a new Rails engine "ProductSearch" and now I have a condition here that I need a controller variable that from Main_app Controller so I am unable to get this variable while executing the action from my Engine APP.

Any Suggestions highly appreciated.

Thanks..!!!

Missing Template error in RUBY ON RAILS

Posted: 25 May 2016 05:57 AM PDT

I made this update button on the edit post page, but when clicked on, it directs to this "missing templates" error page. I checked on google and stack overflow, but all of the answers are code specific. hence I am not able to find the appropriate solution. 1

Missing template posts/update, application/update with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "c:/Sites/myrubyblog/app/views"

add more files with carrierwave

Posted: 25 May 2016 06:22 AM PDT

I have implemented an upload file system with carrierwave on ruby on rails. Currently each user have a single file, how can I do to when the user upload a new file, to add instead of overwrite? Allowing this way the user to have many files (only uploading one at each time)

this is my user controller:

def update #upload personal file

files = current_user.personal_files  files += params[:user][:personal_files]  current_user.personal_files = files  current_user.save    respond_to do |format|    if @user.save     # copy_file   #make a copy of the uploaded file in public/files/data.xml for running in the bat file      format.html { redirect_to :back, notice: 'File was sucessfully uploaded!' }      format.json { render :show, status: :ok, location: @user }        else      format.html { render :edit }      format.json { render json: @user.errors, status: :unprocessable_entity }         end      end    end  

when I add a new file, it appears in the DB: [nil, "new_file"]. appears nil and overwrites the oldfile with the new.

and my view:

<%= form_for current_user, :method => :put, :html => {:multipart => true} do |f| %>        <h4 class="h1-form">Submit your personal performance file in order to WebProcessPAIR analyse your performance problems</h4>        <div class="field-wrap">            <div class="input-group image-preview">            <input type="text" class="form-control txt_color file_text log_placeholder" placeholder="Upload xml file" disabled="disabled">                       <span class="input-group-btn">                 <span class="btn btn-large btn-default  btn-file">          <span class="glyphicon glyphicon-folder-open"></span>      Browse                   <%= f.file_field :personal_files, accept: 'text/xml', multiple: true %>                </span>                         <%= button_tag(:type => 'submit', :class => 'btn btn-info sbmt', :disabled => true) do %>            <i class="glyphicon glyphicon-share-alt"></i> Upload            <% end %>                     </span>          </div>        </div>    <%     end %>  

rails milia current_tenant usage in controllers

Posted: 25 May 2016 04:39 AM PDT

I am using milia gem; how can I see current_tenant.name in all views without adding it to every controller action?

kind of like see devise current_user in all models

How to permit array of array in rails

Posted: 25 May 2016 04:00 AM PDT

I have one request where one of the fields is array of array. parameters

{     "product" => {       "pitch_points"=>{        "adwords"=>{          "search"=>{            "short"=>["qwe"],             "long"=>[["asdadas", "dasdasdas"]]           }         }       }     }   }  

How can we permit this long key?

I have done like this

params.require(:product).permit(     pitch_points: [      adwords: [         search: [           short: [],           long: []         ]       ]     ]  )  

.my output is

{    "pitch_points"=>{      "adwords"=>{        "search"=>{          "short"=>["qwe"],           "long"=>[]        }      }    }  }  

but output is empty long.

Assign a jQuery variable to a Rails session variable

Posted: 25 May 2016 06:49 AM PDT

I have a simple select box with years and values like so

<div id="year_selection_area" class="controls text-center">    <select class="form-control " name="Legislation year" id="dueYear">      <OPTION VALUE='2017' >2017</OPTION>      <OPTION VALUE='2016' >2016</OPTION>      <OPTION VALUE='2015'>2015</OPTION>      <OPTION VALUE='2014' >2014</OPTION>      <OPTION VALUE='2013'>2013</OPTION>      <OPTION VALUE='2012' >2012</OPTION>      <OPTION VALUE='2011'>2011</OPTION>      <OPTION VALUE='2010'>2010</OPTION>      <OPTION VALUE='' DISABLED>MORE YEARS ADDED SOON</OPTION>    </select>  </div>  

i also am assigning selected at the beginning through a mix of jQuery and rails

<% if session[:year_browsing]==nil%>    <% session[:year_browsing] = 2016%>  <% else %>    <%= session[:year_browsing] %>  <%end%>  <script  type="text/javascript">    jQuery(document).ready(function($) {      $('.form-control option[value=<%= session[:year_browsing] %>]').attr('selected','selected');    });  

however I need to change session variable depending on what user clicks I tried an if/else statement but it executes all of the ruby as soon as it gets into that on change function

$( ".form-control" ).change(function() {    alert( $(".form-control").val());    var selectedValue = $(".form-control").val();      if ( selectedValue=='2017'){      <% session[:year_browsing] = 2017 %>    }    else if ( selectedValue=='2016'){      <% session[:year_browsing] = 2016 %>    }    else if ( $(".form-control").val()=='2015'){      <% session[:year_browsing] = 2015 %>    }    else if ( $(".form-control").val()=='2014'){      <% session[:year_browsing] = 2014 %>    }    else if ( $(".form-control").val()=='2013'){      <% session[:year_browsing] = 2013 %>    }    else if ( $(".form-control").val()=='2012'){      <% session[:year_browsing] = 2012 %>    }    else if ( $(".form-control").val()=='2011'){      <% session[:year_browsing] = 2011 %>    }    else if ( $(".form-control").val()=='2010'){      <% session[:year_browsing] = 2010 %>    }    else{      <% session[:year_browsing] = 0 %>    }  });  

Looping through multi-checkbox selections in view

Posted: 25 May 2016 05:48 AM PDT

Aiming to display multiple icons a user checks off when creating a new post in the view.

new.html.erb

<%= check_box_tag 'post[tech_icon][]', 'fa-diamond', checked('fa-diamond'), id: "message_area" %>  <%= check_box_tag 'post[tech_icon][]', 'fa-html5', checked('fa-html5'), id: "message_area" %>  <%= check_box_tag 'post[tech_icon][]', 'fa-css3', checked('fa-css3'), id: "message_area" %>  

show.html.view

<% current_user.posts.each do |post| %>    * bellow only renders one checked selections (the last one checked)    <span><i class="fa <%= post.tech_icon %>"></i></span>      * bellow just renders the selected option text on the screen    <%= post.tech_icon %>   <% end %>  

*** If you have a better title I can throw up there please let me know.

enter image description here

enter image description here

enter image description here enter image description here

Nil values not allowed for gRPC in Ruby (proto3)

Posted: 25 May 2016 03:43 AM PDT

Hi I am using gRPC Ruby plugin to communicate to a service. The proto definition contains(proto3):

uint32 id = 1;  

But, when I assign nil to id, it throws an error - expected number for integral field. But for strings, nil values work fine. How do I allow nil values for integral / float fields?

Fine Uploader with Rails form

Posted: 25 May 2016 03:41 AM PDT

I've recently installed Fine Uploader to our Rails app. I've read documentation and experimented a little with it, but I don't seem to understand how this thing actually works, and because of that, I'm having a lot of problems implementing it.

What I did: Installed it (two ways, one "classical" and the second using the fineuploader gem, which seems to do the same).

Created a coffee file containing this.

$ ->    uploader = new (qq.FineUploader)(      debug: true      element: document.getElementById('fine-uploader')      request: endpoint: '/uploads')      template: 'test-template'  

And that creates an "upload a file" button (which of course does not work, cause there is no configuration to handle this on the server site), but I would like to have this button in the simple-form input field.

Also, templating does not work, I don't really understands why.

Unlucky, documentation lack help for Rails.

I'm open for changing this library to something else, as long as it contains the features that I need which are:

  • pausing and resuming download
  • file chunking (in case of failure, user won't be forced to start over)
  • progress bar (not vital)

Entity Relationship Diagram: How to create a Yelp-kind of app with not just one price-range?

Posted: 25 May 2016 03:36 AM PDT

Im new to Rails and I'm in the middle of sketching up an ERD for my new app. A Yelp-sort of app, where a Client is sorted by price.

So I want one Client to have many priceranges - One Client can both have pricerange $ and Pricerange $$$$ for example. The priceranges are: $ - $$ - $$$ - $$$$ - $$$$$

How would this look in a table? Would I create a table called PriceRange with Range1, Range2, Range3, Range4, Range5 to be booleans?

Doesn't the PriceRange-table need any foreign/primary keys?

PriceRange  Range1 (Boolean)  Range2 (Boolean)  Range3 (Boolean)  Range4 (Boolean)  Range5 (Boolean)  

Seding emails with Devise gem and Mailgun Api

Posted: 25 May 2016 03:27 AM PDT

I want to send automated emails via Mailgun either SMTP or API. The problem is that in tutorials I find they explain how to do that manually e.i creating mailer class etc. For example like that:

def send_simple_message    RestClient.post "https://api:YOUR_API_KEY"\    "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",    :from => "Excited User <mailgun@YOUR_DOMAIN_NAME>",    :to => "bar@example.com, YOU@YOUR_DOMAIN_NAME",    :subject => "Hello",    :text => "Testing some Mailgun awesomness!"  end

This is from official Mailgun documentation.

But I am using Devise gem which has email sending implemented.

For example I want to send password reset email. When I click forgot password and submit my email from logs I see that my email is tried to be sent, but not sent of course, I need to set up email server.

So the question is where is this code for sending recovery email is written in devise, how to override it? I want it to oveeride so it will use Mailgun API for example.

I have already generated registrations_controller.rb using

rails generate devise:controllers registrations

command. So I suppose I am overriding it here? Any suggestions?

How to set a background image on a Rails app using CSS

Posted: 25 May 2016 06:50 AM PDT

I'm building a rails app and trying to set a background image for the welcome page. For some reason the image won't show and I'm not sure why. I've looked at numerous questions on here but I'm still unable to resolve.

Here's my latest code -

welcome.css.scss

body {    background: url('/assets/mamaknowscollage.jpg');  }  

I've also tried (amongst numerous other variations) -

body {    background-image:  url('/assets/mamaknowscollage.jpg');  }  

Here's the html (the image tag here is for the logo)

welcome.html.erb -

<header>      </header>  <body>                  <image><%= link_to image_tag('MamaKnowsLogo.jpg'), root_path, id: "logo" %></image>    </body>  

I've left the url path as is but I've also tried it without assets and it still doesn't work.

Any ideas what I'm doing wrong?

Class in Folder autoloading

Posted: 25 May 2016 03:14 AM PDT

In one of my controllers I would like to use a Service-Class that I located inside of: services/cars/strategies/unload_car_strategy.rb

Although the unload_car_strategy.rb is located inside the folders, I don't want to use namespacing: The class right now looks like this:

class UnloadCarStrategy    ....  end  

When I call in my controller UnloadCarStrategy.new I get the error:

NameError: uninitialized constant UnloadCarStrategy  

How can I instruct Rails to load this Class?

Angular Rails app with authentication and token

Posted: 25 May 2016 03:17 AM PDT

I am building a very simple app using angular js as frontend and rails as backend. When building only using rails, it was simple to use devise gem and work with rails views (erb). But now the scene is entirely different for me. I wish to keep both the codebases in separate repositories and run both servers separately (grunt and rails server). Here are my queries (if somebody could answer)

  1. How to manage authentication ? I tried using angular devise but it was not overriding hostname and port for all requests, I had to do it for all type of requests. Also, devise renders its own views after authentication is complete or if it fails. For sessions#new controller, it never lets me override and does its own work.
  2. Any other recommended approach/ a gist or a tutorial which can guide me to manage sessions between rails/angular js ? I am new to this approach (rails-angular thing)

Thanks alot in advance !

No comments:

Post a Comment