Sunday, October 30, 2016

Jquery datepickers date issue | Fixed issues

Jquery datepickers date issue | Fixed issues


Jquery datepickers date issue

Posted: 30 Oct 2016 07:53 AM PDT

I have a rails application where I am using jquery datepicker with 2 input fields like this.

<input type="text" class="form-control datePicker" placeholder="Check In" id="dpd1" value="<%= (Date.today).strftime('%d-%m-%Y').to_s %>" name="arrival_date_disp">    <input type="text" class="form-control datePicker" placeholder="Check Out" id="dpd2" value="<%= (Date.today + 1).strftime('%d-%m-%Y').to_s %>" name="departure_date_disp">  

Jquery code is like this -

  $("#dpd1").datepicker({      minDate : new Date,      yearRange: "-90:+1",      changeMonth: true,      changeYear: true,      altField  : '#arrival_date',      altFormat : 'yy-mm-dd',      dateFormat : 'dd-mm-yy',      numberOfMonths: 2    });         $("#dpd2").datepicker({      minDate : $("#dpd1").datepicker( "getDate" ),      yearRange: "-90:+1",      changeMonth: true,      changeYear: true,      altField  : '#departure_date',      altFormat : 'yy-mm-dd',      dateFormat : 'dd-mm-yy',      numberOfMonths: 2,      setDate: "31-10-2016"    });  

The problem is there is only one datepicker instance being initialized for both fields and as such when I click open the datepicker it shows same date for both of them (obvious as same datepicker is being used).

How do I show different date for second field ?

first one

second one

Rails global variables are not updating on update

Posted: 30 Oct 2016 07:51 AM PDT

I have an $template variable defined in application_controller.rb which contains some site template code changed thought admin

The problem is when I save or update it, it doesn't affect site till server restart, which is really uncomfortable in production

$template = Template.first  .....    $template.header.html_safe  

In logs I can the that $template variable make and SQL and the very beginning (before Puma booted) and probably that's the way how global vars should be working.

P.S. Im using active_admin and update from there

Embed Shiny app in Rails site

Posted: 30 Oct 2016 07:16 AM PDT

I am trying to create an interactive chart using Shiny, but I cannot find any direction about how to embed the shiny app in a ruby on rails site. Can anyone provide a simple example of how to do this?

Rails eager_load with conditions on association

Posted: 30 Oct 2016 07:09 AM PDT

I have a Rails application which has Stations (weather stations) and Observations. The app shows many weather stations on a map with the current wind speed and direction.

I have a method which is used on the stations#index method which selects the stations and joins the latest observation per station.

class Station < ActiveRecord::Base    has_many :observations    def self.with_observations(limit = 1)      eager_load(:observations).where(        observations: { id: Observation.pluck_from_each_station(limit) }      )    end  end  

Observation.pluck_from_each_station returns an array of ids. The observations table contains many thousands of rows so this is necessary to keep rails from eager loading thousands of records.

This method should return all the stations - whether the have any observations or not. However this is currently not the case.

it "includes stations that have no observations" do    new_station = create(:station)    stations = Station.with_observations(2)    expect(stations).to include new_station # fails  end  

From my understanding a LEFT OUTER JOIN should return all rows wether the there are any results in the joined table or not. Why is this not working as expected?

This is an example of the SQL generated:

SELECT "stations"."id" AS t0_r0,         "stations"."name" AS t0_r1,         "stations"."hw_id" AS t0_r2,         "stations"."latitude" AS t0_r3,         "stations"."longitude" AS t0_r4,         "stations"."balance" AS t0_r5,         "stations"."timezone" AS t0_r6,         "stations"."user_id" AS t0_r7,         "stations"."created_at" AS t0_r8,         "stations"."updated_at" AS t0_r9,         "stations"."slug" AS t0_r10,         "stations"."speed_calibration" AS t0_r11,         "stations"."firmware_version" AS t0_r12,         "stations"."gsm_software" AS t0_r13,         "stations"."description" AS t0_r14,         "stations"."sampling_rate" AS t0_r15,         "stations"."status" AS t0_r16,         "observations"."id" AS t1_r0,         "observations"."station_id" AS t1_r1,         "observations"."speed" AS t1_r2,         "observations"."direction" AS t1_r3,         "observations"."max_wind_speed" AS t1_r4,         "observations"."min_wind_speed" AS t1_r5,         "observations"."temperature" AS t1_r6,         "observations"."created_at" AS t1_r7,         "observations"."updated_at" AS t1_r8,         "observations"."speed_calibration" AS t1_r9  FROM   "stations"         LEFT OUTER JOIN         "observations"         ON "observations"."station_id" = "stations"."id"  WHERE  "observations"."id" IN (450, 500, 550, 600, 650, 700, 750, 800);  

Ruby on Rails building a pivot table

Posted: 30 Oct 2016 06:34 AM PDT

I have a database table stockdiaries. With columns: ID, PRODUCT, UNITS, REASON

Sample values:

1,Apple,5,purchase

2,Orange, 8,purchase

3,Apple,-3,sale

4,Orange,-5,sale

Then this joins products table from where I get product.NAME, product.CATEGORY and so on.

In my view I want to display a table with columns: PRODUCT, SOLD, PURCHASED, STOCK And values:

Apple,3,5,2

Orange,5,8,3

SOLD is the sum of units sold, PURCHASED the sum of units purchased.

I really don't know what is the best approach in the first place. But is it possible to use in my view something like:

<%= stockdiary.product.NAME %>  <%= stockdiary.sold %>  <%= stockdiary.purchased %>  <%= stockdiary.stock %>  

to show the columns I want?

In other words is there a way I can define purchased in my model or controller to calculate sum(UNITS) where REASON=purchase?

If yes what is the syntax to use?

If no what approach should I follow then?

Ruby on Rails - showing all instances in a view, with specific column value, returned by other table column

Posted: 30 Oct 2016 06:10 AM PDT

First, my schema looks like this:

create_table "categories", force: :cascade do |t|  t.text     "name"  t.text     "slug"  end    create_table "fields", force: :cascade do |t|  t.integer  "order"  t.string   "title"  t.text     "tipo"  t.text     "values"  t.integer  "sub_category_id"  end  add_index "fields", ["sub_category_id"], name: "index_fields_on_sub_category_id"    create_table "sub_categories", force: :cascade do |t|  t.integer  "category_id"  t.text     "name"  t.text     "slug"  end  add_index "sub_categories", ["category_id"], name: "index_sub_categories_on_category_id"  

This is my schema, a category has many sub_categories, and a sub_category has many fields. Im trying to generate a view which contains all fields of a specific sub_category, i've already passed the sub_category.id to this view, but thats all i could do.

Its not that difficult i imagine, but im a begginer on rails. How can i do it? The routes are also a problem, since i have to create a new controller function. But the route generated by my application already looks like this: "/sub_categories/mysubcategory56/visualizeform?sub_category=56"

Creating multiple object in rails

Posted: 30 Oct 2016 06:01 AM PDT

I want to make in one form calendar and multiple visits for this calendar (like 10,100,1000) How can i achieve this? How to make multiple objects for calendar in controller?

Rails throws 'load_missing_constant: expected path_to_x to define X', yet it does

Posted: 30 Oct 2016 05:13 AM PDT

My error:

/Users/-/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:512:in `load_missing_constant':   Unable to autoload constant Types::QueryType, expected /Users/-/project/app/graph/types/query_type.rb to define it (LoadError)  

app/graph/schema.rb:

module Graph    Schema = GraphQL::Schema.define do      query Types::QueryType    end  end  

app/graph/types/query_type.rb:

module Graph    module Types      QueryType = GraphQL::ObjectType.define do        name 'Query'      end    end  end  

config/application.rb:

config.autoload_paths << "#{Rails.root}/app/graph"  config.autoload_paths << "#{Rails.root}/app/graph/interfaces"  config.autoload_paths << "#{Rails.root}/app/graph/types"  config.autoload_paths << "#{Rails.root}/app/graph/unions"  

Rails correctly expects Types::QueryType to be defined in app/graph/types/query_type.rb, however - weirdly enough - somehow concludes that file does not define Types::QueryType, which it clearly does.

Even weirder: when jumping into a console, it only throws this error the first time Types::QueryType is requested. The second time however Types::QueryType resolves to the correct definition.

I'm probably doing something wrong here, but I just can't seem to find it.

compared with non class/module in controller

Posted: 30 Oct 2016 04:56 AM PDT

How to only include users who have more than 0 challenges.publish?

class UsersController < ApplicationController    def index      @users, @alphaParams = User.select{ |user| user.challenges.publish > 0}.alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name}    end  end  

Maybe I should use where instead of select?

Rails has_and_belongs_to_many how to change default iforeign key and show list of results on csv

Posted: 30 Oct 2016 05:56 AM PDT

I have tables products and suppliers. And a joining table products_sup.

I have in my model Product:

has_and_belongs_to_many :suppliers, :join_table => "products_sup"  

And in my model Supplier:

has_and_belongs_to_many :products, :join_table => "products_sup"  

In my view I would like to display list of suppliers for each product.

But it returns

Mysql2::Error: Unknown column 'products_sup.product_id' in 'on clause':

Note that NAME is a column in suppliers db table. And products_sup is the joining table.

The problem is that products_sup contains columns PRODUCT, SUPPLIER. While rails by default is looking for supplier_id and product_id. But I can't find the right syntax to change these default columns. The same way that for a belongs_to I would use `:foreign_key => 'custom_foreign_key_column'

What should I use in my view and models to achieve it?

Cannot select element with jQuery rails

Posted: 30 Oct 2016 04:03 AM PDT

I'm migrating a project from Middleman to Rails5 and I have a problem with jQuery. I cannot select a form with jQuery, instead of returning a DOM element it returned a jQuery object. Here's a screenshot of what I mean:

enter image description here

I'm sorry if this is a stupid question but I've been googling for 1 hour and feel pretty desperate right now. I also included jQuery in the manifest file so I cannot think of anything that's wrong with it.

Add Rails minitest fixtures for a single test

Posted: 30 Oct 2016 03:19 AM PDT

Is there a way to a Rails minitest fixtures just for one specific test or set of tests? I ask because I want to display Delayed::Job jobs using the standard index/show/delete schemes so I want to fake some Delayed::Job objects to test my views. But I don't want these objects present when I actually test my Delayed::Job processing code so I'd like to add then just for once specific set of tests.

Rails: use REJECT_IF dependent on parent record and for specific action for nested attributes

Posted: 30 Oct 2016 03:19 AM PDT

In my app I am building to learn Rails and Ruby (am beginner), I have a polymorphic model between tag and annotation / document. These are implemented using nested fields and I need to validate the tag-fields using reject_if.


models set up using

belongs_to :tagable, :polymorphic => true  has_many :tags, :as => :tagable, dependent: :destroy  accepts_nested_attributes_for :tags, allow_destroy: true  

For tags related to annotations, this need to be the validations:

validates :content,             presence: true  validates :tagtype,             presence: true  validates :key,                 on: :update, presence: true, if: 'key_position.blank?' && 'key_regex.blank?'  validates :key_position,        on: :update, presence: true, if: 'key.blank?' && 'key_regex.blank?', format: { with: /(^(-?\d+,\s){3}-?\d+$){1}/, message: 'numeric and as x1, y1, x2, y2'}  validates :key_regex,           on: :update, presence: true, if: 'key_position.blank?'  validates :value_position,      on: :update, presence: true, if: 'value_regex.blank?', format: { with: /(^(-?\d+,\s){3}-?\d+$){1}/, message: 'numeric and as x1, y1, x2, y2'}  validates :value_regex,         on: :update, presence: true, if: 'value_position.blank?'  validate  :valid_key_regex,     on: :update  validate  :valid_value_regex,   on: :update  

def valid_key_regex    @valid_key_regex ||= Regexp.new(self.key_regex)    rescue => exception    errors.add(:key_regex, exception)  end    def valid_value_regex    @valid_value_regex ||= Regexp.new(self.value_regex)    rescue => exception    errors.add(:value_regex, exception)  end  

For tags related to documents, this need to be the validations:

validates :content,             presence: true  validates :tagtype,             presence: true  

I can make two methods for the reject_if of annotations and documents respectively, my questions now are:

  1. how can I check the action (on: :create, on: update...) for the separate attributes?
  2. how do I get specific error messages back to the user when saving the changes (I use simple_form)? (i.e. not reject silently?)
  3. how could I DRY the 2 separate methods in to one (if useful?)? Where to place it and how to check the related parent?

all advice, tips, examples welcome!

Nested loops using Cocoon Gem in Rails

Posted: 30 Oct 2016 03:18 AM PDT

So I'm building a recipe app where is user can create his own dish.

the problem im facing is in cocoon gem i have followed every step on their documentation but while creating the recipe the user is not able to see the nested form for ingredients. the form to fill in the ingredients just does not display. The main form works fine which has image, name and description. it saves displays perfectly. I'm trying to give all the chunks of code that I feel could have problem and could help you simulate my app. Thanks for the Help

code for the simple_form under file name --> _form.html.erb

<div id="panel-body">  <%= f.input :image, input_html: {class: "form-control"} %>  <%= f.input :name, input_html: {class: "form-control"} %>  <%= f.input :description, input_html: {class: "form-control"} %>    <div class="row">      <div class="col-md-6">      <h3>Ingredients</h3>      <div id="Ingredients">        <%= f.simple_fields_for :ingredients do |ingredient| %>          <%= render "ingredient_fields", f: ingredient %>        <% end %>        <div class="links">          <%= link_to_add_association 'Add', f, :ingredients, class: "btn btn-default add-button" %>        </div>      </div>    </div>  

code for the ingredient_fields under the file name --> _ingredient_fields.html.erb

<div class="form-inline clearfix">    <div class="nested-fields">      <%= f.input :name, input_html: {class: "form-input form-control"} %>      <%= link_to_remove_association "Remove", f, class: "btn btn-default form-button"%>    </div>  </div>  

code for the Recipe model

class Car < ApplicationRecord    has_many :ingredients      has_attached_file :image, styles: { medium: "450x250#" }    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/      accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true      validates :name, :description, :image, presence: true  end  

code for Recipe controller

def recipe_params      params.require(:recipe).permit(:name, :description, :image, ingredient_attributes: [:id, :type, :displacment, :power, :torque, :layout, :_destroy])  

aws-sdk 2.3.0 and Paperclip 5.0.0 bad region

Posted: 30 Oct 2016 05:47 AM PDT

Im using the AWS-SDK 2.3.0 gem with paperclip 5.0.0 gem.

In my config/environment/development.rb file i have

config.paperclip_defaults = {      storage: :s3,      s3_region: 'eu-west-1',      s3_credentials: {        bucket: 'myBucketName',        access_key_id: 'xxxxxxxxxxxxxxxxxxxxxx',        secret_access_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'        }      }  

My bucket region in set as Ireland when I created my bucket so according to the document provided by AWS i set my s3 region as eu-west-1.

Im assuming my details are all correct but, when i upload an image, its gets saved to the bucket but it won't show on my rails app. If i right click on open image in new tab i get this error:

<Message>  The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.  </Message>  

Rails add link to edit attribute from another model

Posted: 30 Oct 2016 02:59 AM PDT

If I have a model Product and a model Category.

I have a table in products index showing products with columns like:

 <td><%= product.ID %></td>   <td><%= product.NAME %></td>   <td><%= product.category.NAME %></td>  

It shows values like:

1,salad, vegetable

2,apple,fruit

I want to be able to click on vegetable or fruit to edit them.

I tried:

<td><%= link_to product.category.NAME, [:edit, product.category] %>  

This takes me to a page

categories/1/edit

which returns

Couldn't find Product with 'ID'=

Instead it should go to

categories/edit/1

In my routes I have:

 match ':controller(/:action(/:ID))', :via => [:get, :post]   resources :categories  

What is the correct syntax to use in this case?

Is there a way to namespace a PORO class without a module

Posted: 30 Oct 2016 01:31 AM PDT

Here is my press_post/updater.rb file

class PressPost::Updater    def say_something      p 'hello world'    end  end  

But when I run things I get this ': uninitialized constant PressPost (NameError)

I know that other answers have touched around this.. One went so far as to make an empty module inside the class file on the first line.. That seems flawed.

I know there is a way to not have to do this extra code. I believe it's a config or something, but I don't know how to accomplish this.

Note.. I want to do this because these are in a sub directory and it is a whole lot easier searching the code for PressPost::Updater than Updater

How to trigger conditional if every date attribute is nil for current month of this year?

Posted: 30 Oct 2016 01:24 AM PDT

How to trigger conditional with @future_challenges if deadline is not equal to Date.current.year.month?

controller

@future_challenges = current_user.challenges.unaccomplished.order("deadline ASC").select{ |challenge| challenge.deadline > Date.current if challenge.deadline.present? }  

view

<% if @future_challenges != Date.current.year.month %> # Is giving true even if there are challenges with deadline in current month of this year    <div style="margin-top: -4px;"></div>  <% end %>  

Undefined method "has_attached_file" for my ActiveRecord model

Posted: 30 Oct 2016 12:17 AM PDT

I followed the docs at https://github.com/thoughtbot/paperclip exactly to install implement paperclip in my app for image uploading. I am currently using gem 'paperclip', '~> 5.0.0.beta1'. After I did the migration, the four columns were added onto my schema properly:

t.string   "picture_file_name"  t.string   "picture_content_type"  t.integer  "picture_file_size"  t.datetime "picture_updated_at"  

My paperclip should therefore be installed correctly. However, when I proceeded to add the following two lines onto my model class:

  has_attached_file :picture, styles: { medium: "300*300>", thumb: "100*100" }, default_url: "/images/start_project3.jpg"    validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/  

Everything broke. I try to create, search, or anything related to the model class in rails console, it yells at me with the following error:

NoMethodError: undefined method `has_attached_file' for #<Class:0x0055bd71ec0228>  

I have tried multiple versions of paperclip, from the earlier version 4.3.0 to the latest version of paperclip, but the problem persists. I also restarted my server in between changes and migrations, but that did not fix the problem. This is the migration that I performed:

class AddAttachmentPictureToProjects < ActiveRecord::Migration    def self.up      change_table :projects do |t|        t.attachment :picture      end    end      def self.down      remove_attachment :projects, :picture    end  end  

I am totally lost right now as to what to do. This is my gem file:

source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.7.1'  # Use postgresql as the database for Active Record  gem 'pg', '~> 0.15'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    # Use ActiveModel has_secure_password  gem 'bcrypt', '~> 3.1.7'  gem 'pry-rails'  gem 'annotate'  # Use Unicorn as the app server  # gem 'unicorn'  gem 'faker'  # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development  gem 'pg_search'  gem 'paperclip', '~> 5.0.0.beta1'  # gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git"  # gem "paperclip", "~> 4.3"    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'    gem 'faker'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end    group :production do    gem 'newrelic_rpm'    gem 'rails_12factor' # error feedback  end  

Postgres: Column updated but not detected.

Posted: 29 Oct 2016 11:59 PM PDT

So i initially had a foreign id tutor_id as type string. So i ran the following migrations.

change_column(:profiles, :tutor_id, 'integer USING CAST(tutor_id AS integer)')

The problem is that there was data already created which initially contained the tutor_id as type string. I did read however that by using CAST, the data should be converted into an integer.

So just to confirm i went into heroku run rails console to check the tutor_id of the profiles and tutor_id.is_a? Integer returns true.

However i am currently getting this error

ActionView::Template::Error (PG::UndefinedFunction: ERROR: operator does not exist: integer = text at character 66

Why is that so? Is the only way out to delete the data and to recreate it?

(I'm assuming the information provided above is enough to draw a conclusion, else i will add the relevant information too.)

Why is Capybara still passing when I delete JS file?

Posted: 29 Oct 2016 10:15 PM PDT

I have a small Rails app which Capybara, Rspec and Webkit for testing. It's a CRUD app to create items. I added a feature when user can input the id, then it will show the status of the item is shippable or not. When user enter the id, the app will make a Ajax call to item_path(id), then it will return the status of the item which will append to the view. I wrote test to check if the feature is and it's all passed. I did use bye bug to check the if the status get appended to the view, and I do see it. Then I accidentally DELETE the JavaScript file (items.js in assets). I run the test, all the tests are still passed; I did use byebug to check and I still see the status appended to view even though js file is deleted. Do you why test still pass? Thanks

How to create video viewing site using youtube API and Vimeo API on Ruby on rails

Posted: 29 Oct 2016 08:55 PM PDT

I want to create video viewing site using youtube API and Vimeo API on Ruby on rails.

But I cannot find useful information.

If you know about that in any website or book, let me know please.

Thanks

In Rails, how would I show a 'Goodbye' page that is *only* accessible immediately after the user signs out?

Posted: 29 Oct 2016 10:28 PM PDT

I was recently using Svbtle.com where they show a page immediately after logging out. It says "Goodbye.", along with link to go "Back to SVBTL".

I like the idea of a 'farewell' page, similar to how they did it, and would like to do something similar in a project I'm working on.

The 'farewell' page on Svbtle has a path of https://svbtle.com/notify?logout. When you reload the page or try to navigate to https://svbtle.com/notify?logout, it redirects you to the site landing page.

What is this magic?

How would I go about only showing a page upon user logout, but then prevent them from visiting it otherwise?

I'm using Rails 5.0.0.1 and Devise for authentication.

Display specific user info in app

Posted: 29 Oct 2016 09:02 PM PDT

I'm trying to manipulate user data within my iOS app. I'm using a rails backend and AWS. I have a working user login view where a user inputs their name, email, and password. I'm trying to display a user's name on their post, for example, Created by: Lexie (where 'Lexie' is pulled from the DB). I'm more familiar with user creation in rails, and am looking for a similar action to User.name, User.first_name, etc. Still trying to learn the basics of this process in Swift. Any idea how to pull and display the data by string interpolation in another view? Thanks so much for the help :)!

Here is my viewController code:

//  //  ViewController.swift  //      import UIKit    class ViewController: UIViewController {        @IBOutlet weak var signinBackgroundView: UIView!      @IBOutlet weak var signupBackgroundView: UIView!      @IBOutlet weak var signinEmailTextField: UITextField!      @IBOutlet weak var signinPasswordTextField: UITextField!      @IBOutlet weak var signupNameTextField: UITextField!      @IBOutlet weak var signupEmailTextField: UITextField!      @IBOutlet weak var signupPasswordTextField: UITextField!      @IBOutlet weak var activityIndicatorView: UIView!      @IBOutlet weak var passwordRevealBtn: UIButton!        let httpHelper = HTTPHelper()        override func viewDidLoad() {          super.viewDidLoad()          // Do any additional setup after loading the view, typically from a nib.            self.activityIndicatorView.layer.cornerRadius = 10      }        override func didReceiveMemoryWarning() {          super.didReceiveMemoryWarning()          // Dispose of any resources that can be recreated.      }        @IBAction func passwordRevealBtnTapped(sender: AnyObject) {          self.passwordRevealBtn.selected = !self.passwordRevealBtn.selected            if self.passwordRevealBtn.selected {              self.signupPasswordTextField.secureTextEntry = false          } else {              self.signupPasswordTextField.secureTextEntry = true          }      }        func displaSigninView () {          self.signinEmailTextField.text = nil          self.signinPasswordTextField.text = nil            if self.signupNameTextField.isFirstResponder() {              self.signupNameTextField.resignFirstResponder()          }            if self.signupEmailTextField.isFirstResponder() {              self.signupEmailTextField.resignFirstResponder()          }            if self.signupPasswordTextField.isFirstResponder() {              self.signupPasswordTextField.resignFirstResponder()          }            if self.signinBackgroundView.frame.origin.x != 0 {              UIView.animateWithDuration(0.8, animations: { () -> Void in                      self.signupBackgroundView.frame = CGRectMake(320, 134, 320, 284)                      self.signinBackgroundView.alpha = 0.3                        self.signinBackgroundView.frame = CGRectMake(0, -40, 320, 284)                      self.signinBackgroundView.alpha = 1.0                  }, completion: nil)          }      }        func displaySignupView () {          self.signupNameTextField.text = nil          self.signupEmailTextField.text = nil          self.signupPasswordTextField.text = nil            if self.signinEmailTextField.isFirstResponder() {              self.signinEmailTextField.resignFirstResponder()          }            if self.signinPasswordTextField.isFirstResponder() {              self.signinPasswordTextField.resignFirstResponder()          }            if self.signupBackgroundView.frame.origin.x != 0 {              UIView.animateWithDuration(0.8, animations: { () -> Void in                      self.signinBackgroundView.frame = CGRectMake(-320, 134, 320, 284)                      self.signinBackgroundView.alpha = 0.3;                        self.signupBackgroundView.frame = CGRectMake(0, 134, 320, 284)                      self.signupBackgroundView.alpha = 1.0                    }, completion: nil)          }      }        func displayAlertMessage(alertTitle:String, alertDescription:String) -> Void {          // hide activityIndicator view and display alert message          self.activityIndicatorView.hidden = true          let errorAlert = UIAlertView(title:alertTitle, message:alertDescription, delegate:nil, cancelButtonTitle:"OK")          errorAlert.show()      }        @IBAction func createAccountBtnTapped(sender: AnyObject) {          self.displaySignupView()      }        @IBAction func cancelBtnTapped(sender: AnyObject) {          self.displaSigninView()      }          @IBAction func signupBtnTapped(sender: AnyObject) {          // Code to hide the keyboards for text fields          if self.signupNameTextField.isFirstResponder() {              self.signupNameTextField.resignFirstResponder()          }            if self.signupEmailTextField.isFirstResponder() {              self.signupEmailTextField.resignFirstResponder()          }            if self.signupPasswordTextField.isFirstResponder() {              self.signupPasswordTextField.resignFirstResponder()          }            // start activity indicator          self.activityIndicatorView.hidden = false            // validate presence of all required parameters          if self.signupNameTextField.text != "" && self.signupEmailTextField.text != "" && self.signupPasswordTextField.text != "" {              makeSignUpRequest(self.signupNameTextField.text!, userEmail: self.signupEmailTextField.text!, userPassword: self.signupPasswordTextField.text!)          } else {              self.displayAlertMessage("Parameters Required", alertDescription: "Some of the required parameters are missing")          }      }            @IBAction func signinBtnTapped(sender: AnyObject) {          // resign the keyboard for text fields          if self.signinEmailTextField.isFirstResponder() {              self.signinEmailTextField.resignFirstResponder()          }            if self.signinPasswordTextField.isFirstResponder() {              self.signinPasswordTextField.resignFirstResponder()          }            // display activity indicator          self.activityIndicatorView.hidden = false            // validate presense of required parameters          if self.signinEmailTextField.text != "" &&              self.signinPasswordTextField.text != "" {              makeSignInRequest(self.signinEmailTextField.text!, userPassword: self.signinPasswordTextField.text!)          } else {              self.displayAlertMessage("Parameters Required",                                       alertDescription: "Some of the required parameters are missing")          }      }        func updateUserLoggedInFlag() {          // Update the NSUserDefaults flag          let defaults = NSUserDefaults.standardUserDefaults()          defaults.setObject("loggedIn", forKey: "userLoggedIn")          defaults.synchronize()      }        func saveApiTokenInKeychain(tokenDict:NSDictionary) {          // Store API AuthToken and AuthToken expiry date in KeyChain          tokenDict.enumerateKeysAndObjectsUsingBlock({ (dictKey, dictObj, stopBool) -> Void in              let myKey = dictKey as! String              let myObj = dictObj as! String                if myKey == "api_authtoken" {                  KeychainAccess.setPassword(myObj, account: "Auth_Token", service: "KeyChainService")              }                if myKey == "authtoken_expiry" {                  KeychainAccess.setPassword(myObj, account: "Auth_Token_Expiry", service: "KeyChainService")              }          })            self.dismissViewControllerAnimated(true, completion: nil)      }          func makeSignUpRequest(userName:String, userEmail:String, userPassword:String) {          // 1. Create HTTP request and set request header          let httpRequest = httpHelper.buildRequest("signup", method: "POST",              authType: HTTPRequestAuthType.HTTPBasicAuth)            // 2. Password is encrypted with the API key          let encrypted_password = AESCrypt.encrypt(userPassword, password: HTTPHelper.API_AUTH_PASSWORD)            // 3. Send the request Body          httpRequest.HTTPBody = "{\"full_name\":\"\(userName)\",\"email\":\"\(userEmail)\",\"password\":\"\(encrypted_password)\"}".dataUsingEncoding(NSUTF8StringEncoding)            // 4. Send the request          httpHelper.sendRequest(httpRequest, completion: {(data:NSData!, error:NSError!) in              if error != nil {                  let errorMessage = self.httpHelper.getErrorMessage(error)                  self.displayAlertMessage("Error", alertDescription: errorMessage as String)                    return              }                self.displaSigninView()              self.displayAlertMessage("Success", alertDescription: "Account has been created")          })      }        func makeSignInRequest(userEmail:String, userPassword:String) {          // Create HTTP request and set request Body          let httpRequest = httpHelper.buildRequest("signin", method: "POST",                                                    authType: HTTPRequestAuthType.HTTPBasicAuth)          let encrypted_password = AESCrypt.encrypt(userPassword, password: HTTPHelper.API_AUTH_PASSWORD)            httpRequest.HTTPBody = "{\"email\":\"\(self.signinEmailTextField.text!)\",\"password\":\"\(encrypted_password)\"}".dataUsingEncoding(NSUTF8StringEncoding);            httpHelper.sendRequest(httpRequest, completion: {(data:NSData!, error:NSError!) in              // Display error              if error != nil {                  let errorMessage = self.httpHelper.getErrorMessage(error)                  self.displayAlertMessage("Error", alertDescription: errorMessage as String)                    return              }                // hide activity indicator and update userLoggedInFlag              self.activityIndicatorView.hidden = true              self.updateUserLoggedInFlag()                do {                    let responseDict = try NSJSONSerialization.JSONObjectWithData(data,                      options: NSJSONReadingOptions.AllowFragments) as! NSDictionary                  //var stopBool : Bool                    // save API AuthToken and ExpiryDate in Keychain                  self.saveApiTokenInKeychain(responseDict)              }              catch let error as NSError {                  print(error.localizedDescription)              }              })      }  }  

Creating a login macro for feature specs - Rails

Posted: 29 Oct 2016 07:55 PM PDT

I've seen apps use a macro before for creating logins for feature tests. I'm in the process of building out the configuration for my test suite and this is the final task I was hoping to accomplish. Basically I want to write this line in my tests

login(user)  

Instead of what I'm doing right now.

create(:user)  visit "/"    click_link "Sign In"  expect(current_path).to eql(user_session_path)    fill_in "user_email", with: "robert@example.com"  fill_in "user_password", with: "password"  click_button "Log in"  

If anybody know what I need that would be great! Thank you.

Query table without returning ActiveRecord_Relation

Posted: 29 Oct 2016 07:43 PM PDT

Basically I have an app that have a Projects table, and a project belongs to a Client (and the client has a column in the table for it's location).

I've created a search feature where the idea is you search for the project by location then client. I was hoping to use JavaScript to filter out any clients that weren't from the selected locations. I followed a tutorial to do this, however the tutorial assumed that the client belonged to a location, and therefore I'm the below code doesn't seem to work. Is there a way to basically say 'If Client.location = one of the selected locations, show it'

clients = $('#search_client').html()  $('#search_location').change ->      location = $('#search_location :selected').map(() ->          return $(this).text();      ).get().join().split(',');      console.log(location)      options_array = []      for l in location          options_array.push $(clients).filter('optgroup[label="'+l+'"]').html()      if options_array          $('#search_client').html(options_array.join(''))      else          $('#search_client').empty()  

Rails migration to change column type from text to json (Postgresql)

Posted: 29 Oct 2016 07:16 PM PDT

I've been trying unsuccessfully to change a column type in my Postgres database from text to json. Here's what I've tried...

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0]    def up      execute 'ALTER TABLE places ALTER COLUMN notes TYPE json USING (notes::json)'    end      def down      execute 'ALTER TABLE places ALTER COLUMN notes TYPE text USING (notes::text)'    end  end  

Also...

class ChangeNotesTypeInPlaces < ActiveRecord::Migration[5.0]    def up      change_column :places, :notes, 'json USING CAST(notes AS json)'    end      def down      change_column :places, :notes, 'text USING CAST(notes AS text)'    end  end  

Both of these return the same error...

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type json  

Making dates go back passed 2011 DateTime Generator on Ruby on Rails Scaffold

Posted: 30 Oct 2016 08:11 AM PDT

I am making a new site and I cannot get dates in a generated scaffold to go back passed 2011. The months , days, and time work perfectly. However, I cannot moved the year past back 2001. I am making an Astrology Porn site with a database of compatible female pornstars with an inputted zodiac sign. I hope you can help me fix the date issues I am trying to add Kianna Dior to the zodiac sign and she was born in 1969, so it will not work with rails 5 default generator for any dateTime columns that are generated via scaffold.

How do I convert this to a UJS request?

Posted: 29 Oct 2016 05:35 PM PDT

I have a Profile and that has_many :ratings.

I have a set of JS controls that control the input of that rating on the profile looks like this:

enter image description here

What I want to happen is whenever the controls are moved, it automagically updates the rating on that profile the background -- via UJS (or w/e is best per Rails 5).

This is in my Profile#Show view:

<div class="col-md-3">    <div class="profile-data">      <table class="table table-condensed">          <tbody>          <tr>              <td>                  <p>                    <button type="button" class="btn btn-danger m-r-sm slider-step-value" id="slider-step-value-speed">5</button>                    Speed                  </p>                  <div class="slider"></div>              </td>              <td>                  <p>                    <button type="button" class="btn btn-primary m-r-sm slider-step-value" id="slider-step-value-tackling">3</button>                    Tackling                  </p>                  <div class="slider"></div>              </td>          </tr>          <tr>              <td>                  <p>                    <button type="button" class="btn btn-success m-r-sm slider-step-value" id="slider-step-value-dribbling">9</button>                    Dribbling                  </p>                  <div class="slider"></div>              </td>              <td>                  <p>                    <button type="button" class="btn btn-danger m-r-sm slider-step-value" id="slider-step-value-passing">7</button>                    Passing                  </p>                  <div class="slider"></div>              </td>          </tr>          </tbody>      </table>    </div>  </div>  

This is my profiles.js:

$(document).on('turbolinks:load', function() {    var sliders = $('.slider');    var buttons = $('.slider-step-value');      for ( var i = 0; i < sliders.length; i++ ) {      var button = $(sliders[i]).prev('p').find('button')[0];        noUiSlider.create(sliders[i], {        start: 5,        step: 1,        behaviour: 'tap',        connect: [true, false],        range: {          'min':  1,          'max':  10        }      });        attachEvent(sliders[i], button);    }      function attachEvent(slider,button){      slider.noUiSlider.on('update', function( values, handle ) {        button.innerText = parseInt(values[handle]);      });    }    });  

How do I convert this to use UJS to update this record without needing a form?

Rails Geocoder gem & Google Autocomplete API - Query Limit Reached

Posted: 30 Oct 2016 08:09 AM PDT

I have tried to implement Google's autocomplete API, when user types a location and presses to enter, A map with markers load in another page. It looks exactly like Airbnb. Search, then map..

My problem is, lately I am getting an error of "query size limit reached". I have read all the posts about this issue here but could not find a solution.

Basically, when user types an address as string, I get that string and use it for google maps' init lat & long. I use geocoder gem and server as Heroku.

Here is how it looks like;

@search = params[:search]  if !@search.nil? && @search.strip != ""        location =  Geocoder.search(params[:search])      @initlat = location[0].latitude      @initlng = location[0].longitude   end  

Why I am getting this error and how can I solve it?

No comments:

Post a Comment