Tuesday, October 11, 2016

mongoid .where queries not working as expected | Fixed issues

mongoid .where queries not working as expected | Fixed issues


mongoid .where queries not working as expected

Posted: 11 Oct 2016 07:43 AM PDT

I have a model that belongs_to another:

class Permission    include Mongoid::Document    belongs_to :action    field :action_id, type: String  

And a corresponding has_many model:

class Action    include Mongoid::Document    has_many :permissions  

I am seeing that 2 basic ActiveRecord queries are not working:

First, sending the object instead of the object id does not work:

action = Action.first  permissions = Permission.where(action: action)  permissions.count # this is always 0  

However, if I use the id, it works fine:

Permission.where(action_id: action.id) # this works fine  

Second, sending an array of ids does not work, ever:

Permission.where(action_id: [action.id]) # always empty  

Does mongoid not support basic ActiveRecord queries? If not, for the first problem, I can work around it by always using the object id, but for the second, how do I search by an array of targets?

Thanks for any help, Kevin

Multiple Devise Models resource_name error

Posted: 11 Oct 2016 07:37 AM PDT

Error I am getting is undefined method `login' for Model1:0x007f2a914d0d10 although in the form i am passing resouce2 and resource_name2 then why is it saying undefined method login for Model1

here is my model2

 attr_accessor :login        devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable,:authentication_keys => [:login]  

applicationhelper

def resource_name  :user1  end    def resource  @resource ||= Model1.new  end  def resource_name1    :user2  end    def resource1    @resource ||= Model2.new  end  

login form

<%= form_for(resource1, as: resource_name1, url: session_path(resource_name1)) do |f| %>                      <!--showing fields-->              <div class="row">                <div class="col-xs-offset-1 col-xs-6 field">                   <p><%= f.label :login %><br />                  <%= f.text_field :login ,class: 'form-control' ></p>                </div>                </div>                <div class="row">                <div class="col-xs-offset-1 col-xs-6 field">                </div>                </div>                <div class="row">                <div class="col-xs-offset-1 col-xs-6">                  <% if devise_mapping.rememberable? -%>                      <div class="field">                        <%= f.check_box :remember_me %>                        <%= f.label :remember_me %>                      </div>                  </div>                <% end -%>                </div>  

Change angular-materials md-tooltip text dynamically through controller

Posted: 11 Oct 2016 07:26 AM PDT

I am rendering the following HTML which introduces a tooltip by Angular-Material and an input-field which gets initialized as DatePicker.

- content_for :top_datepicker do    .toolbar-icons      md-tooltip md-direction="bottom" initial text      input#range-picker.dashboard-daterange-picker.no-margin[type="text"        placeholder="#{@start_date.strftime("%d.%m.%Y")} - #{@end_date.strftime("%d.%m.%Y")}"      ]  

As you can see it is inside a content_for block by Rails and gets rendered outside the corresponding controller. Due to the nature of the current state the application is in, we have to handle it like this.

Inside our Angular-Controller we want to change the text of this tooltip based on certain conditions. We further use jQuery to manipulate the respective part of the DOM.

The following represents how the above code will render in HTML:

<div class="toolbar-icons" aria-label="perf.data is DISABLED">      <input class="dashboard-daterange-picker no-margin" id="range-picker" placeholder="21.10.2015 - 11.10.2016" type="text" disabled="">  </div>  

The following code gets called to ultimately manipulate the tooltip:

updateDatePicker = ->    el = $scope.el    isDisabled = $scope.isDisabled()      if isDisabled      el.parent().attr("aria-label", "DISABLED")      el.prop('disabled', true)    else      el.parent().attr("aria-label", "ENABLED")      el.prop('disabled', false)  

Unfortunately the change does not have an effect on the tooltips text. While the aria-label is getting changed, the text displayed is not.

If you have any input on this, it'd be highly appreciated! Thanks in advance!

From Rails Tutorial Ch8 - why is instance variable not used?

Posted: 11 Oct 2016 07:30 AM PDT

module SessionsHelper      # Logs in the given user.    def log_in(user)      session[:user_id] = user.id    end      # Returns the current logged-in user (if any).    def current_user      @current_user ||= User.find_by(id: session[:user_id])    end      # Returns true if the user is logged in, false otherwise.    def logged_in?      !current_user.nil?    end  end  

Currently working through Hartl's Rails Tutorial in Ch 8 where he gets you to write code for users to log in and stay logged in.

Under method logged_in?, why is local variable current_user used instead of @current_user?

Run my own code only after started the rails server

Posted: 11 Oct 2016 07:34 AM PDT

I know initializers and config.after_initialize do ... end do the job, but when running rake tasks, they also get run.

The question is, how can I run my own code only after started the rails server?

No confirmation messages after submit

Posted: 11 Oct 2016 07:07 AM PDT

I'm working in a Rails 4.1.0 application in cloud9 IDE. I enter test info in the fields: Name, Email, Comments, in the Contact Us form page, clicked submit and the following info displays in the address bar with no 'Message sent' confirmation:

https://manual-coder-rails/contacts?utf8=%E2%9C%93&contact%5Bname%5D=Nick&contact%5Bemail%5D=victorysupplys%40gmail.com&contact%5Bcomments%5D=Nice+web&commit=Submit

I entered no info in the fields (blank), clicked submit, the blank info is displayed in the address bar, again no 'Error' confirmation message:

https://manual-coder-rails/contacts?utf8=%E2%9C%93&contact%5Bname%5D=&contact%5Bemail%5D=&contact%5Bcomments%5D=&commit=Submit

I enter bundle exec rails c and Contact.all in the console, no entries are listed here and no entries are saved to the database:

Contact Load (2.9ms) SELECT "contacts".* FROM "contacts" => #

I tried to figure out what the problem is in my code, having made several changes, but to no avail. Someone might notice something I do not. Here is my code for perusal and advice:

New.html.erb

        <div class="row">            <div class="col-md-4 col-md-offset-4">               <div class="well">                 <%= form_for @contact, :method => :get do |f| %>               <div class="form-group">                  <%= f.label :name %>                  <%= f.text_field :name, class: 'form-control' %>               </div>               <div class="form-group">                  <%= f.label :email %>                  <%= f.email_field :email, class: 'form-control' %>               </div>               <div class="form-group">                  <%= f.label :comments %>                  <%= f.text_area :comments, class: 'form-control' %>               </div>                  <%= f.submit type="Submit", class: "btn btn-default" %>               <% end %>              </div>          </div>       </div>  

Contacts_controller.rb

        class ContactsController < ApplicationController            def new              @contact = Contact.new            end                            def index            end                def create              @contact = Contact.new(contact_params)                  if @contact.save                  name = params[:contact][:name]                  email = params[:contact][:email]                  comments = params[:contact][:comments]                  ContactMailer.contact_email(name, email, comments ).deliver                    flash[:success] = "Message sent."                  redirect_to new_contact_path                else                  flash[:danger] = "Error occured, message has not been sent."                  redirect_to new_contact_path                end            end              private              def contact_params                params.require(:contact).permit(:name, :email, :comments)              end            end  

routes.rb

          Rails.application.routes.draw do               resources :contacts, only:[:new, :create], path_names: { new: ""}               get '/about' => 'pages#about'               root 'pages#home'  

application.html.erb

           <div class="container">                <% flash.each do |key, value| %>                <div class="alert alert-<% key %> alert-dismissable">                  <button type="button", class="close", data-dismiss="alert", aria-label="Close"><span aria-hidden="true"></span>&times;></span></button>                  <%= value %>                 </div>                 <% end %>              <%= yield %>          </div>        </body>     </html>  

How do I overcome "unknown encoding name - macintosh" error with Nokogiri?

Posted: 11 Oct 2016 07:12 AM PDT

I'm using Rails 4.2.7. I'm currently using the following logic to parse a doc with Nokogiri …

      content.xpath("//pre[@class='text-results']").xpath('text()').to_s      

In my HTML document, this content appears within my "text-results" block …

<pre class="text-results"><html xmlns:o="urn:schemas-microsoft-com:office:office"  xmlns:w="urn:schemas-microsoft-com:office:word"  xmlns="http://www.w3.org/TR/REC-html40">    <head>  <meta name=Title content="&lt;p&gt;&lt;a href=http://mychiptime">  <meta name=Keywords content="">  <meta http-equiv=Content-Type content="text/html; charset=macintosh">…  

I include this section because my parsing dies with the following error …

Error during processing: unknown encoding name - macintosh  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node.rb:627:in `find'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node.rb:627:in `serialize'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node.rb:786:in `to_format'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node.rb:642:in `to_html'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node.rb:512:in `to_s'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node_set.rb:187:in `block in each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node_set.rb:186:in `upto'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node_set.rb:186:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node_set.rb:218:in `map'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/node_set.rb:218:in `to_s'  /Users/davea/Documents/workspace/myproject/app/services/onlinerr_service.rb:8:in `pre_process_data'  /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:77:in `process_my_object_data'  /Users/davea/Documents/workspace/myproject/app/services/onlinerr_my_object_finder_service.rb:82:in `process_my_object_link'  /Users/davea/Documents/workspace/myproject/app/services/abstract_my_object_finder_service.rb:29:in `block in process_data'  /Users/davea/Documents/workspace/myproject/app/services/abstract_my_object_finder_service.rb:28:in `each'  /Users/davea/Documents/workspace/myproject/app/services/abstract_my_object_finder_service.rb:28:in `process_data'  /Users/davea/Documents/workspace/myproject/app/services/run_crawlers_service.rb:18:in `block in run_all_crawlers'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/relation/delegation.rb:46:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/relation/delegation.rb:46:in `each'  /Users/davea/Documents/workspace/myproject/app/services/run_crawlers_service.rb:5:in `run_all_crawlers'  

Is there any way to make Nokogiri ignore this unknown encoding? I'm trying to get the content inside the "pre" tag as text, so I don't need it parsed further.

Edit: I'm on Mac El Capitan. Per the comment, here's my locale settings

davea$ locale  LANG="en_US.UTF-8"  LC_COLLATE="en_US.UTF-8"  LC_CTYPE="en_US.UTF-8"  LC_MESSAGES="en_US.UTF-8"  LC_MONETARY="en_US.UTF-8"  LC_NUMERIC="en_US.UTF-8"  LC_TIME="en_US.UTF-8"  LC_ALL=  

login devise teacher model using TeacherID while student model using email

Posted: 11 Oct 2016 06:41 AM PDT

Is it possible to allow one devise model login on basis of the username or some other unique id while other one using default devise email authentication process.

Can a private channel communication happen between two Pusher Apps

Posted: 11 Oct 2016 06:15 AM PDT

I have two iOS apps, lets call it Agent app and Customer App. I have a chat feature between these two apps, but the chats need to be recorded on the server.

I have created two Pusher Apps, one for each of the iOS apps. They both subscribe to their respective private-{id}-channel.

Now every time a message is generated from say Agent app (via HTTP request to server), I want server to create a pusher event with Agent's message on Customer's private channel.

Is it possible to achieve the above using Pusher Private channels?

Rails PSQL JSON query: find the nested array element at unknown position?

Posted: 11 Oct 2016 06:31 AM PDT

Please see an example here: http://edgeguides.rubyonrails.org/active_record_postgresql.html#json

How do I get all the records containing "jack" inside change array?

I can currently do it with such a query:

Event.where("payload #>> '{change,0}' = 'jack' ")  

But what if I don't know the exact "jack"'s position (0 in this case) inside change array? How to rearrange the Rails PSQL query then?

Rails 5 - data validation gems

Posted: 11 Oct 2016 07:27 AM PDT

In my app that I am building to learn RoR, I want to start learning more about validations. Besides building custom validations (e.g. using regex), I was wondering what the best gems are for commonly found validations for data like addresses, currencies, dates/time formatting, languages, etc.? This in order to build a basic set to use on new apps.

I came across these below to use:

How about incoterms, unit of measure (from UNECE or ISO20022) or VAT id? Any other ones that I should look at?

How Do I Implement a Popover in a Rails Partial Using Bootstrap 3?

Posted: 11 Oct 2016 05:12 AM PDT

I currently have a Rails 4 application running Bootstrap 2 (gem twitter-bootstrap-rails 2.2.8). I was successful in implementing a popover using partials where a map is displayed when a link is clicked. Here is the code that I have.

application.js

//= require jquery  //= require jquery_ujs  //= require twitter/bootstrap  //= require_tree .  

bootstrap.js.coffee

jQuery ->    $(".popover-map").popover({ html : true })  

_map

<div class="row-fluid">    <div class="span4" align="center" id="text-bold"><%= link_to("#{t :map_marfa_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_marfa_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_marfa'}") %></div>    <div class="span4" align="center" id="text-85"><%= "#{t :map_msg_click}" %></div>    <div class="span4" align="center" id="text-bold"><%= link_to("#{t :map_bigbend_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_bigbend_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_bigbend'}") %></div>  </div>  

_map_marfa

<p align="center"><%= image_tag("map-marfa.jpg", alt: "#{t :map_marfa_head}") %></p>  

_map_bigbend

<p align="center"><%= image_tag("map-bigbend.jpg", alt: "#{t :map_bigbend_head}") %></p>  

When I click either link the map display below and stays there until the person clicks the link again to close the map. I have copied the code to my new Rails 5 Bootstrap 3 application. Here are the code changes for Bootstrap 3.

application.js

//= require bootstrap-sprockets  

bootstrap.js.coffee was renamed to bootstrap.coffee

//= require jquery  //= require jquery_ujs  //= require turbolinks  //= require_tree .  //= require bootstrap-sprockets  

_map

<div class="row">    <div class="col-md-4" align="center" id="text-bold"><%= link_to("#{t :map_marfa_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_marfa_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_marfa'}") %></div>    <div class="col-md-4" align="center" id="text-85"><%= "#{t :map_msg_click}" %></div>    <div class="col-md-4" align="center" id="text-bold"><%= link_to("#{t :map_bigbend_head}" , '#', class: "popover-map", rel: "popover", title: "#{t :map_bigbend_head}", :"data-placement" => "bottom", :"data-content" => "#{render 'pages/map_bigbend'}") %></div>  </div>  

Now when I click either link the map displays and immediately disappears instead of staying until the link is clicked.

URI.parse(url).open not working on heroku

Posted: 11 Oct 2016 04:45 AM PDT

So I just added the option to upload images by url using this action

@stock = Stock.create    @stock.url = params[:url]    @stock.image = URI.parse(  params[:url]  ).open    @stock.user = current_user    @stock.save    respond_to do |format|     format.html     format.js    end  

and it's working in development but not in heroku. I'm using paperclip to save he images on AWS.

I'm not getting any errors too. I tried without .open it worked in development but not in heroku. Any thoughts on this?

Rails remove column that has no data type

Posted: 11 Oct 2016 05:22 AM PDT

In my Rails 5 application I've accidentally created a column with no data type. Database is SQLite.

create_table "students", force: :cascade do |t|   t.integer  "club_id"   t.string   "email"   t.datetime "created_at",      null: false   t.datetime "updated_at",      null: false   t.string   "picture"   t.integer  "payment_plan_id"   t.         "activity"   t.index ["club_id"], name: "index_students_on_club_id"  end  

When I attempt rails db:rollback I get this error:

Rhys-MacBook-Pro:classmaster Rhys$ rails db:rollback == 20161011105423 AddActivitiesRefToStudents: reverting =======================  -- remove_column(:students, :activity, :reference)  rails aborted! StandardError: An error has occurred, this and all later migrations canceled: undefined method `to_sym' for nil:NilClass  

I've tried running this migration:

class RemoveColumn < ActiveRecord::Migration   def up     execute "ALTER TABLE students DROP COLUMN activity";   end  end    

But I think SQLite doesn't support dropping columns. Is there a fix for this?

Workaround help! Alternatives to using .where on ActiveRecord associations?

Posted: 11 Oct 2016 06:37 AM PDT

I'm using a gem and can't seem to use .where to filter a collection of records without losing access to the gem's methods.

I'm looking for a workaround solution for a query such as:

User.includes(:addresses).where("addresses.country = ?", "Poland").references(:addresses)

Are there any alternatives to using .where in this situation? Filtering the records on a simple find_by or find(id) seems to retain the gem's methods, but I don't know how / if this can be used when the condition is on an associated model.

Can anyone help? Thanks!

Use a carousel as a form element

Posted: 11 Oct 2016 04:36 AM PDT

I'm working on a object where as part of a form I'd like the user to be able to select from a number of images in a carousel. I can then access the index of the carousel using come javascript, though I'm not sure how to then pass that to the model when the form is submitted?

Any help would be greatly appreciated.

  function submit(){      carouselIndex = $('.carousel-inner').find('.active').index()      console.log(carouselIndex)      //hiddenInput.value=selectedImageInCarousel;      return validateForm();    }  

Rails activejob with Sidekiq is spawning multiple jobs on perform_later

Posted: 11 Oct 2016 03:49 AM PDT

I have an fairly simple Rails 5 app for monitoring sites speeds. It sends jobs off to an external page speed testing service and periodically checks to see if the jobs are complete, and if so it calls and stores the data about the page.

Each project can have many pages, and each page can have many jobs, which is where the response from the testing service is stored.

There is an activejob, with a sidekiq backend, that is supposed to run every minute, check for pages that are due to run, and if any are found launch a job to enqueue it. It also checks if there are any enqueued jobs, and if they are found, it spools up a job to check the status and save data if it's complete.

def perform()   #Todo:- Add some way of setting the status into the view and check for active here - no way to stop jobs at the mo!  pagestorun = Page.where("runtime < ?", DateTime.now)    pagestorun.each do |page|    job = Job.new(:status => "new")    page.jobs << job    updatedatetime(page)  end     if pagestorun.count != 0    #Run the queuejob task to pick out all unqueued jobs and send them to webpagespeedtest    QueuejobsJob.perform_later   end  

#Check any jobs in the queue, then schedule the next task GetrunningtasksJob.perform_later FindjobstorunJob.set(wait: 1.minute).perform_later() end

This seems to work as expected for a while, but after 5 minutes or so two jobs seem to end up spawning at the same time. Eventually each of those spawn more of their own, and after a few days I end up with tens of thousands trying to run per hour. There's no errors or failing jobs as best I can tell, I can't find any reason why it'd be happening. Any help would be mundo appreciated :)

rails how to get the following query in rails

Posted: 11 Oct 2016 04:41 AM PDT

I need to get the following output in rails how do i do it?

SELECT "booking_rooms".* FROM "booking_rooms" INNER JOIN "bookings" ON "bookings"."id" = "booking_rooms"."booking_id" WHERE "booking_rooms"."room_id" IN (22, 27, 21) AND ("bookings"."start_date" <= '2016-10-16' AND "bookings"."end_date" > '2016-10-12')  

I tried:

BookingRoom.joins(:booking).where(room_id: self.booking_rooms.map(&:room_id), bookings: { start_date:self.end_date,end_date:self.start_date})  

Get a model reference from ActiveRecord_Associations_CollectionProxy object

Posted: 11 Oct 2016 04:41 AM PDT

I have two Active Record Models

class User < ActiveRecord::Base    has_many :posts  end    class Post < ActiveRecordd:Base  end  

I would like to get the reference of the class Post from the activerecord association.

user.posts.get_object_class  

Currently when I do

user.posts.class.to_s   # Post::ActiveRecord_Associations_CollectionProxy  

Is there a way I can get Post without having to "split" the string on "::" and then constantize it ?

wrong number of arguments Contact#create

Posted: 11 Oct 2016 03:40 AM PDT

I have this error :

ArgumentError in Contact#create

wrong number of arguments (given 0, expected 2)

it show me this line from my view

  <%= @contact.errors.full_message.each do |message| %>  

My create method in contact_controller take no arguments

contact_controller.rb

  def index      @contact = Contact.all    end      def create      @contact = Contact.new(contact_params)      if @contact.save        flash[:notice] = "Welcome"        redirect_to "/"      else        flash[:alert] = "You filled wrong the form"        render 'connection'      end    end  

and i'm supposed to display those message from my model

contact.rb

validates :firstname, presence: true, length: { maximum: 30, minimum:2,      too_long: "30 characters is the maximum allowed.", too_short: "2 characters is the minimum allowed." }    validates :lastname, presence: true, length: { maximum: 50, minimum:2,      too_long: "50 characters is the maximum allowed.", too_short: "2 characters is the minimum allowed." }    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i  validates :email, presence: true, uniqueness: {message: "Email is already subscribed"}, length: { maximum: 40, minimum:7,      too_long: "40 characters is the maximum allowed.", too_short: "7 characters is the minimum allowed.",},      format: { with: VALID_EMAIL_REGEX }    validates :password, presence: true, length: { maximum: 30, minimum:6,      too_long: "30 characters is the maximum allowed.", too_short: "6 characters is the minimum allowed." }  

I do not understand what arguments ruby wants. anyone know what is it ?

Devise yielding password in plain text?

Posted: 11 Oct 2016 03:02 AM PDT

I just stumpled upon something strange while writing specs for my User model (using Devise 4.2.0):

password = 'password'  user = User.create!(email: 'test@test.dk', password: password)    user.password  # => 'password'  

How is this even possible?

Its not visible in the create statement:

 SQL (0.7ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["email", "test@test.dk"], ["encrypted_password", "$2a$11$J.VxqiCi/4uJP/RPbz9EFe48qMiYKU5QJtn.7zlxNd5RJ/JLTfFd6"], ["created_at", 2016-10-11 09:48:50 UTC], ["updated_at", 2016-10-11 09:48:50 UTC]]  

But nevertheless accessible from the console?

Anyone who can shed some light on whats happening here?

Ruby on Rails - Editor only for code

Posted: 11 Oct 2016 02:50 AM PDT

In my previous applications I have used WYSIWYG editor for Bootstrap gem when it comes to text editing.

Now I am building a application where only codes will be edited (mostly js code).

Problem with WYSIWYG editor for Bootstrap gem is that it doesn't have any code markup/colors or lines for code.

Can I achieve this without any gem/plugin and/or what is the best option if I need to use gem/plugin.

Something like image below

enter image description here

Rails how to version the models?

Posted: 11 Oct 2016 05:50 AM PDT

I have created rails application using rails 5 and ruby 2.3.
I want to add few changes in some model files and save it as new application. I want two run both applications in production as two similar applications. I know how to version the controller by using namespace but I didn't get solution for version rails models.

js doesn't load properly with ruby on rails

Posted: 11 Oct 2016 06:39 AM PDT

On my index I have <a href="/dashboard/gov.html">Government dashboard</a> which links to my gov page, and on my gov page I have google map api and my own javascripts. But only one of my own js works fine when I click the link to gov page. The odd thing is if I just reload gov.html(or set it as root) in stead of click the link to redirect all seem work fine.

Here is the html part which doest work:

<div  id='map'  style='height:280px; width:400px' />      <script  src="https://maps.googleapis.com/maps/api/js?key=XXX"></script>      <script>          var  map  =  new  google.maps.Map(document.getElementById('map'),  {                      center:  new  google.maps.LatLng(31.267401,  121.522179),                      mapTypeId:  google.maps.MapTypeId.ROADMAP,                      zoom:  11                  });                                    var  t  =  new  Date().getTime();          var  waqiMapOverlay  =  new  google.maps.ImageMapType({                      getTileUrl:  function(coord,  zoom)  {                                return  'http://tiles.aqicn.org/tiles/usepa-aqi/'  +  zoom  +  "/"  +  coord.x  +  "/"  +  coord.y  +  ".png?token=_TOKEN_ID_";                      },                      name:  "Air  Quality",            });            map.overlayMapTypes.insertAt(0,waqiMapOverlay);    </script>        </th>      <th><img id="imgtraffic" width="395" height="280" /></th>    </tr>  </table>    <table align="center" width="811" border="1">    <tr>      <td bgcolor="#9AD7F1" width="811">City Heat Map</td>    </tr>    <tr>      <td><div id="container"></div>       <div class="button-group">        <input type="button" class="button" value="Show heat map" onclick="heatmap.show()"/>        <input type="button" class="button" value="Close heat map" onclick="heatmap.hide()"/>      </div>      <script>          var map = new AMap.Map("container", {          resizeEnable: true,          center: [116.418261, 39.921984],          zoom: 11      });      if (!isSupportCanvas()) {           ...      </script>        </td>    </tr>  </table>  

Thanks a lot for your help.

Undefined local variable or method Rails4.2

Posted: 11 Oct 2016 02:24 AM PDT

Im new in RoR and I need your help. Here is my problem;

  1. I wanted to post an email notification after user click on Submit button.

  2. I got an error called undefined local variable or method `leave_application' for #

Here is my code.

Controller

def create  @leave_application = LeaveApplication.new(leave_application_params)   respond_to do |format|    if @leave_application.save      Notification.new_leave_application(@leave_application).deliver_now      format.html { redirect_to leave_applications_path, notice: 'Leave application submitted. Now pending for approval.'}      format.json { render action: 'show', status: :created, location: @leave_application }    else      flash[:error] = 'Failed to create leave.'      format.html { render action: 'new' }      format.json { render json: @leave_application.errors, status: :unprocessable_entity }    end  end    else      flash[:danger] = error      redirect_to :back and return    end  end  

Mailer

 class Notification < ActionMailer::Base      def new_leave_application leave_id, approved_by_id, user_id      @receiver = User.find(approved_by_id) rescue nil      @sender = User.find(user_id)      @leave = LeaveApplication.find(leave_id)      @hr = User.where('role = ?', 'hr').map{|u| u.email }      @hr << @sender.email  if @receiver.blank?    mail(to: @receiver.email, subject: "New Leave Application")  else    mail(to: @sender.email,  bcc: @hr, subject: "New Leave Application")    end  end  

Image

Thank you.

Selenium+Ruby issue because of page reload

Posted: 11 Oct 2016 03:16 AM PDT

I've the following code:

wait.until {driver.find_element(:xpath, "//input[@class='btn btn-success Testserver']")}  element = driver.find_element(:xpath, "//input[@class='btn btn-success Testserver']")  element.click  wait.until {driver.find_element(:xpath, "//input[@class='btn btn-success Testserver2']")}  element = driver.find_element(:xpath, "//input[@class='btn btn-success Testserver2']")  element.click  

My problem is the 3rd and the 4th line. When selenium clicks the first element, it causes a page reload. The problem is that the 4th line (the wait.until) finds the element BEFORE the reload is executed. So what happens? Selenium thinks the element is already loaded, it try to continue and after that the pages reload and selenium throw out an error, cause it can't find the element.

Selenium::WebDriver::Error::StaleElementReferenceError: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed.  

What can i do? The code works fine when i put a sleep between this lines, but i don't wan't to use sleep cause of bad practice. Is there another way?

Thanks for your help!

Rails favicon on deeply nested routes

Posted: 11 Oct 2016 01:49 AM PDT

I have the following

= favicon_link_tag 'favicon.png', type: 'image/png'  

And it just works with routes

domain  domain/something  domain/something/something-else  

And does not work with

domain/something/something-else/something-else-else  

favicon.png sits in assets/images and I just copied to public folder as well, but it does not make difference. Also there is no error in inspector (chrome) and between heads

<link rel="shortcut icon" type="image/png" href="/assets/favicon-03c4561b380d44711cadcddd0d4f668034292e937928636e2f18ee3eee81369c.png">  

Looks like it picks the image up, but it does not render it or what? And yes, eventually I don't see icon generated in chrome bar (I see the following):

enter image description here

Rubymine - connect to database in docker container

Posted: 11 Oct 2016 01:16 AM PDT

I successfully set up my development environment for a Rails project using Docker: the server runs in a container and the database in another linked container.

Here is my docker-compose.yml:

version: '2'  services:    database:      image: postgres:9.3      environment:        POSTGRES_USER: 'postgres'        POSTGRES_DATABASE: 'myapp_development'    web:      build: .      command: rails s -p 3000 -b '0.0.0.0'      volumes:        - .:/myapp      ports:        - "3000:3000"      depends_on:        - database      environment:        RAILS_ENV: 'development'  

Now is there any way I can connect to my development database from within Rubymine?

how to watch a sass file

Posted: 11 Oct 2016 02:43 AM PDT

I just decided to start learning sass but am still struggling a bit to run sass on my pc.I downloaded and installed it already as the pictures show:

enter image description here

enter image description here

The folder that I have the project is inside the htdocs folder in the xampp folder. I typed C:\Users\Thulani>sass --watch C:\xampp\htdocs\ruby\lib\sass\style.scss:style.css on the command line but it only says sass is watching for changes.

enter image description here

How can I actually make changes in my style.scss and see those changes?

Here my html:

<html>  <head>     <title> Import example of sass</title>     <link rel="stylesheet" type="text/css" href="style.css"/>  </head>  <body>     <h1>Simple Example</h1>     <h3>Welcome to TutorialsPoint</h3>  </body>  </html>  

Please help

Ruby on Rails - old version deployment

Posted: 11 Oct 2016 01:15 AM PDT

How to deploy a ruby on rails version 1.x application on a ubuntu server with Apache and Phusion passenger. Since it's a very old version I don't find any documentation and guides.

Also, wondering about setting it up locally as there's no Gemfile.

No comments:

Post a Comment