Tuesday, September 27, 2016

Using many dynamic Google Maps on modals on the same page - Rails | Fixed issues

Using many dynamic Google Maps on modals on the same page - Rails | Fixed issues


Using many dynamic Google Maps on modals on the same page - Rails

Posted: 27 Sep 2016 07:43 AM PDT

I have a shops page with 12 stores. Each store has a button to show it's individual position on the map. The problem is it's not working (I get the same position on every map, it's supposed to be dynamic).

What I'm doing is loading a map inside the ruby block for each shop (Map is loading 12 times - 12 requests to the Google API):

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBktelhtX7My2gbXhZIR8J9Lu6XXXQ1nNM">  </script>    <script type="text/javascript">      var LocationData = [          [<%= shop.latitude %>, <%= shop.longitude %>, '<%= shop.direction %>']      ];      var map;        function initialize() {          var mapOptions = {              zoom: 3          };          var map = new google.maps.Map(document.getElementById('map-canvas-<%= shop.id %>'),              mapOptions);          var bounds = new google.maps.LatLngBounds();          var infowindow = new google.maps.InfoWindow();              for (var i in LocationData) {              var p = LocationData[i];              var latlng = new google.maps.LatLng(p[0], p[1]);              bounds.extend(latlng);              var image = 'assets/marcador_sushi.png';                var marker = new google.maps.Marker({                  position: latlng,                  icon: image,                  map: map,                  title: p[2]              });                google.maps.event.addListener(marker, 'click', function() {                  infowindow.setContent(this.title);                  infowindow.open(map, this);              });          }            map.fitBounds(bounds);      }        google.maps.event.addDomListener(window, 'load', initialize);  </script>  

Rails scopes with hash syntax

Posted: 27 Sep 2016 07:43 AM PDT

Here are my two models:

class Author < ApplicationRecord    has_many :articles  end    class Article < ApplicationRecord    belongs_to :author    scope :articles_by_author, ->(author_id) {joins(:author).where(author: {id: author_id})}  end  

I am trying to get the Article.articles_by_author(id) scope to work. Basically: It should return all the articles for a particular Author.

Here is what happens:

First I grab an author:

author = Author.first  

Then I run the query:

Article.articles_by_author(author)  

The generated SQL seems right:

SELECT "articles".*   FROM "articles"   INNER JOIN "authors"   ON "authors"."id" = "articles"."author_id"   WHERE "author"."id" = 1  

But it errors out with the following:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: author.id: SELECT "articles".* FROM "articles" INNER JOIN "authors" ON "authors"."id" = "articles"."author_id" WHERE "author"."id" = 1

What am I messing up within this scope? I want to keep the hash syntax within this scope.

Core php for multi-tenant application and recommended php framework which is compatible with php 5.3

Posted: 27 Sep 2016 07:19 AM PDT

I was planning to develop my upcoming multi-tenant application on Laravel but my client's server configuration is just PHP 5.3 and current versions of Laravel do not support PHP 5.3, I also looked for Codeigniter and Yii but their latest versions are also not supporting PHP 5.3 and ofcourse in 2016 no new framework is going to support it but my client can't upgrade it as he has his websites running on it. He is asking me to develop the application on CORE PHP so please I would like to have experts advice will it be a good idea to develop multi-tenant application(separate databases for each customer and single code base for all) on CORE PHP on PHP v5.3? Also, please suggest about Ruby on Rails but there will be a learning curve for me as I have no experience of RoR.

Your suggestions will be highly appreciated.

Thank you.

Can you define multiple actions with the same name in Rails?

Posted: 27 Sep 2016 07:22 AM PDT

In asp.net MVC, you can define multiple action methods with the same name, as long as the arguments (the method signature in other words) is different. Can you do this in Rails, or do you have to settle with switch statements inside the same action?

rake db:migrate error (Migrations are pending)

Posted: 27 Sep 2016 07:16 AM PDT

I have been searching for a solution to my problem and haven't had any luck. I am a beginner following a tutorial and I reached a point where I had to run the command 'rake db:migrate' and keep getting an error.

$ rake db:migrate  == 20160927120721 CreateTodoItems: migrating ==================================  -- create_table(:todo_items)  rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    undefined method `refrences' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x0055d8b19b8298>  Did you mean?  references  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:5:in `block in change'  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:3:in `change'  NoMethodError: undefined method `refrences' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x0055d8b19b8298>  Did you mean?  references  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:5:in `block in change'  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:3:in `change'  Tasks: TOP => db:migrate  (See full trace by running task with --trace)  

I have tried to reset the rake with 'rake db:reset' but it tells me that there is a pending migration and to try 'rake db:migrate'. I also tried 'rake db:drop' 'gem update rake' 'bundle update rake' 'bunlde exec rake db:migrate' and still no luck. Can someone assist me with this? I am very new to all of this so if there's anything more I can post please let me know so I can continue to grow and learn! Thanks in advance!!

Ubuntu 16.04LTS
Rails 4.2.6
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

Error when trying to use ruby gem- NameError (uninitialized constant RightScraper::Scraper)

Posted: 27 Sep 2016 07:44 AM PDT

I am trying to use a ruby gem called right_scraper. I have added the gem to my gem file and it installs fine. I used the example code from the gems github page (https://github.com/rightscale/right_scraper)

require 'rubygems'  require 'right_scraper'    scraper = RightScraper::Scraper.new(:basedir => '/tmp', :kind => :cookbook)  scraper.scrape(:type => :git, :url => 'git://github.com/rightscale/right_scraper.git')  

running this code returns the following error:

NameError (uninitialized constant RightScraper::Scraper)  

Does anyone know whats going wrong?

"undefined method `user' for nil:NilClass"

Posted: 27 Sep 2016 07:13 AM PDT

Hello everyone I am new to rails and for some reason I keep getting an error

"undefined method `user' for nil:NilClass".

I have pasted an image of the error on the bottom and I posted the code below.

-Thank you.

Image Error

Controller (registeredapps_controller) create#action:

class RegisteredappsController < ApplicationController     def create     @registeredapp = Registeredapp.new(registeredapp_params)     @registeredapp.user = current_user      unless RegisteredappPolicy.new(current_user, @registeredapp).create?      flash[:alert] = "not authorized"       redirect_to user_registeredapps_path(current_user.id)    end      if @registeredapp.save      flash[:notice] = "You successfully registered your app."      redirect_to user_registeredapp_path(current_user.id, @registeredapp.id)    else      flash.now[:alert] = "There was an error registering your app. Please try again."      render :new    end  end  

Policies (using Pundit Gem) registeredapp_policy.rb

class RegisteredappPolicy       def initialize(user, registeredapp)      @registeredapp = registeredapp      @user = user    end      def create?      if @user.present?       @user = @registerdapp.user      else       false    end  end  

Here are my models

User.rb

class User < ApplicationRecord      # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable, :confirmable      def avatar_url(size)      gravatar_id = Digest::MD5::hexdigest(self.email).downcase      "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}"    end      has_many :registeredapps  end  

Registeredapp.rb

class Registeredapp < ApplicationRecord    belongs_to :user    has_many :events  end  

passing jquery dattimepicker to sqlite database in Ruby on Rails

Posted: 27 Sep 2016 07:03 AM PDT

So i have a Jquery DataTimePicker implemented and do not know how to pass this field into my Database.

Just need some basic help, not even sure where to begin. Any help is greatly appreciated

This is what i have as far as code goes.

<div class="field">  <%= f.label :start_date %>  <input id="datetimepicker" type="text" >  <script type="text/javascript">    jQuery('#datetimepicker').datetimepicker();  </script>  </div>  

Using Rails 3.2.22 and Mongoid 2.5.1 with Mongo 3.2

Posted: 27 Sep 2016 06:54 AM PDT

I am attempting to upgrade our legacy rails/mongo application. Our production Mongodb is 2.4 and we would like to upgrade to 3.2 and still use Mongoid. We use auth on the development database as follows

mongo <host> -usome_user -psome_pwd --authenticationDatabase "some-database"  

The Mongoid.yml file for Mongoid 2.5.1 doesn't seem to have the ability to pass the authentication database parameter, and the authentication fails when trying to perform a rake command, or even get into the rails console.

So my question is this, IS there a way to set the default authentication database so that this parameter does not need to be passed along? If not, then is there a way I can edit my 2.5.1 mongoid.yml so include this information? I am guessing the I will have to upgrade the whole nine yards to a version of Mongoid which can support Mongodb 3.2

Below is the pertinent part of the YML file: development: <<: *defaults hosts: - - - - port: database: username: password:<%= SOME_CREDENTIALS[:mongo][:password] %> max_retries_on_connection_failure: 1

Categories Filter doesn't work as expected - Rails 4

Posted: 27 Sep 2016 07:28 AM PDT

In my app you can search a "tuto" by keywords or by category. When a category is selected all the tutos belonging to this category should be displayed... But it doesn't work...( ALL tutos from ALL categories remain displayed...)

What am I missing? Help would be very welcome, thanks in advance.

I've created my categories name in the console like so

Category Load (1.5ms)  SELECT "categories".* FROM "categories"   => #<ActiveRecord::Relation [#<Category id: 1, name: "Ruby", created_at: "2016-09-26 09:03:17", updated_at: "2016-09-26 09:03:17">, #<Category id: 2, name: "Rails 4", created_at: "2016-09-26 09:03:25", updated_at: "2016-09-26 09:03:25">, #<Category id: 3, name: "Rails 5", created_at: "2016-09-26 09:03:30", updated_at: "2016-09-26 09:03:30">, #<Category id: 4, name: "Heroku", created_at: "2016-09-26 09:03:35", updated_at: "2016-09-26 09:03:35">, #<Category id: 5, name: "AWS-Amazon", created_at: "2016-09-26 09:03:43", updated_at: "2016-09-26 09:03:43">]>  2.3.1 :006 >  

Here is my model with the scopes:

class Tuto < ActiveRecord::Base    acts_as_votable    belongs_to :user    belongs_to :category    validates :category_id, presence: true      scope :ruby,   -> { where(category_id: 1)}    scope :rails4, -> { where(category_id: 2)}    scope :rails5, -> { where(category_id: 3)}    scope :heroku, -> { where(category_id: 4)}    scope :aws,    -> { where(category_id: 5)}      def self.search(search)      if search        where(["title LIKE ?","%#{search}%"])      else        all      end    end  end  

my controller, everything happen in the action index

class TutosController < ApplicationController    before_action :authenticate_user!, only: [:new, :create]    before_action :set_tuto, only: [:show, :edit, :update, :destroy, :upvote]        def index      if params[:search]        @tutos = Tuto.search(params[:search]).includes(:user, :category)      else        @tutos = Tuto.all.includes(:user, :category)      end        @categories = if params[:category].present?        case params[:category]        when "ruby"          Category.ruby        when "rails4"          Category.rails4        when "rails5"          Category.rails5        when "heroku"          Category.heroku        when "aws"          Category.aws        else          Category.all        end      end    end        def show      @tuto = Tuto.find(params[:id])      @user = User.all    end      def new      @tuto = Tuto.new    end      def edit    end      def create        @tuto = Tuto.new(tuto_params)      @tuto.user_id = current_user.id        respond_to do |format|        if @tuto.save          flash[:success] = "Test"          format.html { redirect_to @tuto, notice: 'Tuto was successfully created.' }          format.json { render :show, status: :created, location: @tuto }        else          format.html { render :new }          format.json { render json: @tuto.errors, status: :unprocessable_entity }        end      end    end      def update      respond_to do |format|        if @tuto.update(tuto_params)          format.html { redirect_to @tuto, notice: 'Tuto was successfully updated.' }          format.json { render :show, status: :ok, location: @tuto }        else          format.html { render :edit }          format.json { render json: @tuto.errors, status: :unprocessable_entity }        end      end    end        def destroy      @tuto.destroy      respond_to do |format|        format.html { redirect_to tutos_url, notice: 'Tuto was successfully destroyed.' }        format.json { head :no_content }      end    end        def upvote      @tuto.upvote_by current_user      redirect_to :back    end        private          def set_tuto        @tuto = Tuto.find(params[:id])      end        def tuto_params        params.require(:tuto).permit(:title, :content, :id, :user_id, :category_id)      end  end  

EDIT

and the intersting part of my view, index.html.slim

 .container    .row      h1.text-gray Tutorials     .row.search_banner      .col-xs-3        =form_tag tutos_path, :method => 'get' do           =text_field_tag :search, params[:search],  placeholder:"Search by keywords"          =submit_tag "Search", class:'btn btn-xs btn-default btn-search'      .col-xs-3        =form_tag '/tutos', method: 'get' do          = select_tag :category, options_for_select(["ruby", "rails4", "rails5", "heroku", "aws"], :selected => params[:category])                  = submit_tag "Filter", class:"btn btn-xs btn-default btn-search"        .col-xs-3        -if user_signed_in?          = link_to "Create a tuto", new_tuto_path, class:"btn btn-success"        br        br          #tutos.transitions-enabled    -@tutos.each do |tuto|      .box.panel-default        = link_to image_tag(image_by_category(tuto.category.try(:name))), tuto_path(tuto)            h3 = link_to tuto.title, tuto_path(tuto), class:"title-link"             h6           | Created by:          span<>          = tuto.user.full_name        br        span.glyphicon.glyphicon-heart        span<>        = tuto.get_upvotes.size  

In my select tag the Chose a categorydoesn't appear I have rubythat appears first of the list... I found some help on other topics, I believe I messed it a bit...

Access id of nested object after creation

Posted: 27 Sep 2016 07:31 AM PDT

I 'm creating an object through nested attributes in rails and I need to access this object after the creation on the same method.

@contact.update(contact_params)  

This line sometimes creates a child (an address). Is there any way to get the address id if there is one?

Why Ruby (or Rails) do things like this? (Unexpected model methods without "self" behavior)

Posted: 27 Sep 2016 06:56 AM PDT

I've got a validator in ActiveRecord model, in which I faced with some realy strange behavior.

Example:

if status_changed?    p status # output on line below    # <= "my_status_1"    p my_conditions_1 # output on line below    # <= false      if my_conditions_1      errors.add(:status, 'Error1')      status = status_was    end      p status # output on line below    # <= nil      # my_conditions_2 depends on "status variable"    if my_conditions_2      errors.add(:status, 'Error2')      status = 2    end  end  

Second condition always failed, because status somehow was setted to nil. But when I changed status to self.status everything started working as expected.

Can someone explain it? Because I don't really get what's going on here. And I don't want to live in fear of missing self in models.

ruby, send invitation to message [on hold]

Posted: 27 Sep 2016 06:28 AM PDT

I would like to know if it's possible that you help me . I try to create a systeme who enable to send an invitation for speak. i have 1 user A who want to speak with user B User A send an invitation as notification to User B, User B open notification witch return on a page where they have 2 choice possible accept or don't accept if User B accept they can conversation open else invitation DELETE.

So i have create my model "add" "user" " conversation" "notification" i need only a methode for my Add controller for send invitation as notification .

ty.

Cleaning API Controllers by separating Swagger from the controllers

Posted: 27 Sep 2016 07:21 AM PDT

I'm using Swagger as a UI for my rails API. That means that in my API controllers, I have a lot of swagger blocs of code, making my files hard and heavy to read. I'm looking for a way to separate concerns.

This is what I had:

In my controllers/api/v1/stuffs_controller.rb

module Api    module V1      class StuffsController < BaseController        has_scope :by_category, type: :array        has_scope :by_stuff_type, type: :array        has_scope :by_device_type, type: :array        before_action :set_stuff, only: [:show, :like, :unlike, :desire, :undesire]          swagger_controller :stuffs, 'Stuffs'              swagger_api :index do          summary 'Get all the stuffs'          param :query, :by_category, :string, :optionnal, "Category"          param :query, :by_stuff_type, :string, :optionnal, "Stuff Type"          param :query, :by_device_type, :string, :optionnal, "Device Type"          param :query, :s, :array, :optionnal, "Search Terms"        end          def index          render json: collection, each_serializer: Api::V1::Stuff::IndexSerializer, include: ['categories', 'users.devices', 'stuffs.categories', 'user', 'user.devices.device_model'], status: 200, root: nil        end        end    end  end  

And it's like that for every action in every controller :s

I tried creating modules to encapsulate Swagger UI logic and clean up a little bit my controllers. This is what I came up with (that doesn't work):

In controllers/api/v1/stuffs_controller.rb:

module Api    module V1      class StuffsController < BaseController        include SwaggerStuffs          has_scope :by_category, type: :array        has_scope :by_stuff_type, type: :array        has_scope :by_device_type, type: :array        before_action :set_stuff, only: [:show, :like, :unlike, :desire, :undesire]          swagger_controller :stuffs, 'Stuffs'              SwaggerStuffs.call_index        def index          render json: collection, each_serializer: Api::V1::Stuff::IndexSerializer, include: ['categories', 'users.devices', 'stuffs.categories', 'user', 'user.devices.device_model'], status: 200, root: nil        end        end    end  end  

Then in lib/swagger_modules/recipes_controller_module.rb:

module SwaggerStuffs    def self.call_index      swagger_api :index do        summary 'Get all the stuffs'        param :query, :by_category, :string, :optionnal, "Category"        param :query, :by_stuff_type, :string, :optionnal, "Stuff Type"        param :query, :by_device_type, :string, :optionnal, "Device Type"        param :query, :s, :array, :optionnal, "Search Terms"      end    end  end  

This produces the following error when I try to use swagger UI or restart the server:

uninitialized constant Api::V1::StuffsController::SwaggerStuffs (NameError)  

I added config.autoload_paths += %W(#{config.root}/lib) in my config/application.rb file, but the same error appears.

Is there something I am missing ? Is it a good practice to separate swagger logic from my controllers ?

Thanks :)

Bootsy rails gem not showing images in production

Posted: 27 Sep 2016 06:22 AM PDT

I'm using bootsy (https://github.com/volmer/bootsy) to make formatting my Blog article body much easier. When I upload files in the WYSIWYG editor locally I can view them later just fine; however, when I am in production and do this all the img tags link to

/uploads/bootsy/image/1/image_name.jpeg  

Instead, the path should be a aws s3 url. I am using s3 with carrierwave = for some other things (the post main image url), and I'm not having any problems. I imagine there is some kind of config I need to do to work in production.

Remove devise email validation

Posted: 27 Sep 2016 06:09 AM PDT

I use devise and devise-token-auth. I have User model with following content

class User < ApplicationRecord      devise :database_authenticatable, :registerable,            :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]    include DeviseTokenAuth::Concerns::User      validates_uniqueness_of :login    validates_presence_of :full_name      protected    def email_required?      puts "email_required called"      false    end  end  

but devise email validation is still working

2.3.0 :003 > user = User.new(login: "hello", password: "11111111", password_confirmation: "11111111", full_name: "hello world")   => #<User id: nil, provider: "email", uid: "", email: nil, full_name: "hello world", login: "hello", created_at: nil, updated_at: nil>   2.3.0 :004 > user.valid?  email_required? called   #<===== my method is called!     (3.7ms)  SELECT COUNT(*) FROM "users" WHERE "users"."provider" = $1 AND "users"."email" IS NULL  [["provider", "email"]]    User Exists (1.0ms)  SELECT  1 AS one FROM "users" WHERE "users"."login" = $1 LIMIT $2  [["login", "hello"], ["LIMIT", 1]]   => false   2.3.0 :005 > user.errors   => #<ActiveModel::Errors:0x000000028e2338 @messages={:email=>[...]}, @details={:email=>[{:error=>:blank}]}>  

Why this? Thanks

Rails - Stripe::InvalidRequestError in Bookings#new Must provide source or customer

Posted: 27 Sep 2016 06:06 AM PDT

I'm getting the above error in my Rails app. I have the following Stripe code in my Booking model -

begin    charge = Stripe::Charge.create(      amount: total_amount,      currency: "gbp",      source: self.stripe_token,       description: "Booking created for amount #{total_amount}")    self.stripe_charge_id = charge.id    save!    rescue Stripe::CardError => e    errors.add(:base, e.message)    false  end  

I don't understand why I'm getting the error when I'm clearly including source within my stripe code. I've expressed it above as self.stripe_token but I've tried just stripe_token but still get the same error. My understanding is I need to provide either source or customer, not both, and that it needs to be source rather than customer.

What am I missing?

Devise error - ActionController::InvalidAuthenticityToken

Posted: 27 Sep 2016 05:59 AM PDT

Got problem in devise logout while admin and user logged in same page

For example i logged as user in chrome browser and logged as admin in the same browser,when i logged out of admin session the user session is automatically logged out and redirect to sign in page.
When i try to login as user it's successfully logged in and goes to the admin login page and try to log-in it shows -

ActionController::InvalidAuthenticityToken  

Gitlab CE 8.9 to 8.10 Upgrade Failed

Posted: 27 Sep 2016 05:51 AM PDT

I've been updating my server through the newer GitLab versions, I was at 6.7 yesterday in the evening, and currently I'm up to 8.10.

Currently when starting the GitLab service, Sidekiq fails with "Could not find ace-rails-ap-4.1.0 in any of the sources". I've done all that I can to verify that that gem exists in the vendor sources along with gitlab, but no luck. log/sidekiq.log is as follows:

/usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find ace-rails-ap-4.1.0 in any of the sources (Bundler::GemNotFound)      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/spec_set.rb:85:in `map!'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/spec_set.rb:85:in `materialize'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/definition.rb:114:in `specs'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/definition.rb:159:in `specs_for'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/definition.rb:148:in `requested_specs'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/environment.rb:18:in `requested_specs'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/runtime.rb:13:in `setup'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler.rb:120:in `setup'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/setup.rb:17:in `<top (required)>'      from /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'  

Using Ruby 2.3.1, Ubuntu 14.04.

Postgres: What does @@ mean?

Posted: 27 Sep 2016 07:17 AM PDT

Recently I've found a piece of code for ruby on rails which should search string like like-operator:

scope :search, -> (query) { where('name @@ :q', q: query) }  

But couldn't find any documentation about it.

The operator doesn't work as expected. So what exactly it does?

Change ActiveRecord error blank message for all models

Posted: 27 Sep 2016 05:34 AM PDT

I know that custom error message can be added in locale .yml file like this:

    errors:        models:          user:            attributes:              name:                blank: "The field is required"  

How do I change error blank message for all the models at a time?

Find count of predefined words using active record or pure postgres query

Posted: 27 Sep 2016 05:43 AM PDT

I want to get some text analysis. As a result I want to get count of some key words in all records like this:

answer id: 1, text: 'some good text'

answer id: 2, text: 'some really bad text, angry angry angry text'

and result should be like this:

good: 1, bad: 1, angry: 3

I don't want to select all records and then map them count this key words on ruby etc because of big amount of data. Also I find some solution:

Answer.pluck('regexp_matches(text, \'\mMyKeyword\M\', \'gi\')').flatten.count

Works fine for 1 keyword. This causes problem that I used to do database request per keyword. I'm using rails 4 and potgres. Any help appreciated

Ruby on Rails rmagick Error

Posted: 27 Sep 2016 07:17 AM PDT

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /home/indiba3/.rvm/rubies/ruby-2.1.8/bin/ruby -r ./siteconf20160927-26485-11i89l1.rb extconf.rb  checking for gcc... yes  checking for Magick-config... no  checking for pkg-config... yes  Package MagickCore was not found in the pkg-config search path.  Perhaps you should add the directory containing `MagickCore.pc'  to the PKG_CONFIG_PATH environment variable  No package 'MagickCore' found  checking for outdated ImageMagick version (<= 6.4.9)... *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/home/indiba3/.rvm/rubies/ruby-2.1.8/bin/ruby    extconf failed, exit code 1    Gem files will remain installed in /home/indiba3/.rvm/gems/ruby-2.1.8/gems/rmagick-2.15.4 for inspection.  Results logged to /home/indiba3/.rvm/gems/ruby-2.1.8/extensions/x86-linux/2.1.0/rmagick-2.15.4/gem_make.out    An error occurred while installing rmagick (2.15.4), and Bundler cannot continue.  Make sure that `gem install rmagick -v '2.15.4'` succeeds before bundling.  

My Ruby Version is:ruby-2.1.8 [ i686 ] Rails Version is: 4.2.4

I have cloned a new project.Whenever i run bundle install command i get the above error.Because of this error i'm unable to run my project.So pls help.

Speed up rake task by using typhoeus

Posted: 27 Sep 2016 05:12 AM PDT

So i stumbled across this: https://github.com/typhoeus/typhoeus

I'm wondering if this is what i need to speed up my rake task

Event.all.each do |row|      begin    url = urlhere + row.first + row.second    doc = Nokogiri::HTML(open(url))    doc.css('.table__row--event').each do |tablerow|      table = tablerow.css('.table__cell__body--location').css('h4').text      next unless table == row.eventvenuename        tablerow.css('.table__cell__body--availability').each do |button|          buttonurl = button.css('a')[0]['href']          if buttonurl.include? '/checkout/external'            else          row.update(row: buttonurl)        end        end    end    rescue Faraday::ConnectionFailed      puts "connection failed"    next    end  end  

I'm wondering if this would speed it up, Or because i'm doing a .each it wouldn't?

If it would could you provide an example?

Sam

Querying Postgres Table with JSONB data

Posted: 27 Sep 2016 05:04 AM PDT

I have a Table which stores data in a JSONB column.

Now, what i want to do is, query that table, and fetch records, which have specific values for a key.

This works fine:

SELECT "documents".*  FROM "documents"  WHERE (data @> '{"type": "foo"}')  

But what i want to do is, fetch all the rows in the table, which have types foo OR bar.

I tried this:

SELECT "documents".*  FROM "documents"  WHERE (data @> '{"type": ["foo", "bar"]}')  

But this doesn't seem to work.

I also tried this:

SELECT "documents".*  FROM "documents"  WHERE (data->'type' ?| array['foo', 'bar'])  

Which works, but if I specify a key like so data->'type' it takes away the dynamicity of the query.

BTW, I am using Ruby on Rails with Postgres, so all the queries are going through ActiveRecord.

Rails 4.1: Spacing Issues when using HAML

Posted: 27 Sep 2016 07:26 AM PDT

enter image description hereFirst time HAML wth Ruby on Rails , I want to align the average no of comments with the months. So the first one aligns but not the rest.

screenshot of table so far

monthly.stats.html.haml

.row    .col-md-3      Month    .col-md-9      - 6.times.reverse_each do |i|        %th= i.month.ago.strftime('%b %y')        %tr          - 6.times do            %td &nbsp;        .col-md-3      Av. No of Comments    .col-md-9      - 6.times.reverse_each do |i|        %tr #{@monitor.average_number_of_comments(i.months.ago, Time.now)}        %tr          - 6.times do            %td &nbsp;

I am using

%tr    - 6.times do      %td &nbsp;  

for spaces but this is not spacing correctly

Is there any difference between '/' and '' routes?

Posted: 27 Sep 2016 05:28 AM PDT

Is there a difference between these 2 Rails routes:

get '/', to: 'demo#index'  

vs.

get '', to: 'demo#index'  

Both seem to match the root.

How to internationalise jQuery DataTables in Rails 4 app

Posted: 27 Sep 2016 05:13 AM PDT

in order to display some data we use jQuery datatables. So far we implemented full internationalisation of our app (I18n) except for table features like pagination or search bar descriptions. I don't seem to fully understand the way I18n works and on which event I would have to update the link to the DataTables localisation JSON in order to dynamically update the language property of my DataTable object. I tried the following...

  // Global variable to track localisation path state    var json_for_current_locale = localisation_json_url();      // Hardcoded mappings of Rails locale codes to DataTable language names    function locale_to_language(locale) {      language_codes = {        "en": "English",        "de": "German"      };      return language_codes[locale]    }      function localisation_json_url() {      return 'https://cdn.datatables.net/plug-ins/1.10.12/i18n/' + locale_to_language("<%= I18n.locale %>") + '.json';    }      jQuery('<WHAT TO CAPTURE HERE?>').<WHAT EVENT TO LISTEN TO HERE?>(..., function(){      json_for_current_locale = localisation_json_url();    });      jQuery('#places').DataTable({      "language": { "url": json_for_current_locale },      "pageLength": 50,      "columnDefs": [        {          "targets": [ 0 ],          "sortable": false,          "searchable": false        },        {          "targets": [ 3 ],          "sortable": false,        }      ]    });  

I hope the problem is described appropriately. Thanks for any hints!

best Andi

Ruby on Rails 5 : how to create a web service delivering nested attributes?

Posted: 27 Sep 2016 05:45 AM PDT

I am developing a RoR5 application to provide crypto keys to various applications, through a web service. My RoR application manages Users, and nested Ciphers (using nested attributes). A cipher has a name, and a value (string).

I wish to expose a web service to deliver the requested key:

1 - The client application provides a User and a Cipher name to the web service

2 - The web service returns the Cipher value

I am not expert in RoR, but I have the intuition that I should start by defining a new route for this service. Here is the current routes.rb:

Rails.application.routes.draw do    get 'sessions/new'      root   'sessions#new'    get    '/login',   to: 'sessions#new'    post   '/login',   to: 'sessions#create'    delete '/logout',  to: 'sessions#destroy'    resources :users  end  

Hints on how to structure the application and references are welcome !

Rails 4,Setting up CSS Background Image

Posted: 27 Sep 2016 05:20 AM PDT

I want to set a background image via CSS background: url() property. But it doesn't working. There is nothing special. I have done;

-rails new myApp  -rails g controller Welcome index.  

Thats it. I have this div <div class="image">

And the css for it.

.image{      background: url('image.jgp');  }    

I have image.jgp on my assets/images folder.I can do <%= image_tag('assets/image.jgp') and it works.But CSS part doesn't.` How this problem could be solved?

No comments:

Post a Comment