Wednesday, October 26, 2016

Create databases with Postgres for a cloned application | Fixed issues

Create databases with Postgres for a cloned application | Fixed issues


Create databases with Postgres for a cloned application

Posted: 26 Oct 2016 07:44 AM PDT

I cloned a BitBucket repository and now I would like to create only the development and test databases (excluded production) specified in config/database.yml.

What are the differences between the following commands?

rails db:create  rails db:create:all  rails db:setup  

Double compression on gziped sitemap on elastic beanstalk rails

Posted: 26 Oct 2016 07:29 AM PDT

I have a rails application running on AWS elastic beanstalk. For sitemap generation I am using this sitemap generator gem. The setup in my sitemap.rb file is really basic:

SitemapGenerator::Sitemap.default_host = ENV['SERVER_ROOT']   SitemapGenerator::Sitemap.create do     add '/pages/help'     add '/pages/packing'     add '/pages/privacy'     add '/pages/security'     #...  end   

The sitemap gets generated by a cron job. To deliver the sitemap I have added this rule in my routes.rb:

match '/sitemap.xml.gz', :to => proc {|env| [200, {}, [File.open(Rails.root.join('public', 'sitemap.xml.gz')).read]] }, via: :get  

The file will be delivered to the browser but as it seems it is gzipped twice. Unpacking sitemap.xml.gz results in another .gz archive. Unpacking that will result in the correct sitemap.xml file.

Am I doing anything wrong? What is causing the second compression? How can I prevent it?

Cucumber-rails - Remove gem and all dependencies

Posted: 26 Oct 2016 07:25 AM PDT

Is it possible to remove a gem and automatically all their dependencies?

If it is possible, how can I do that?

How to call controller function from javascript generated button in Rails 4 app?

Posted: 26 Oct 2016 07:09 AM PDT

I have integrated Stripe.js in my rails app. The app produces "Pay with Card" button. I would like to know how can I call a controller function for calling Stripe APIs for receiving payment.

show.html.erb:

<div class="col-xs-12">          <div class="btn-group pull-right" role="group" aria-label="..." style="margin-top:10px;">              <%= link_to 'Back to Products', products_path, class: "btn btn-default btn-info" %>      <%= button_to 'Pay with Card',      <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"        data-key="<%= Rails.configuration.stripe[:publishable_key] %>"        data-description="A month's subscription"        data-amount= "<%= @shopping_cart.total*100 %>"        data-locale="auto"></script> %>        <!--      <button type="button" class="btn btn-default btn-success">        <span class="fa fa-shopping-cart"></span>        &nbsp;Checkout      </button> -->          </div>      </div>  

shopping_carts_controller.rb

def checkout    @shopping_cart.process_payment stripe_params    redirect_to products_path    flash[:notice] = "Succefully made payment."  end  

How can I call the checkout method?

Testing a gem that uses ActiveRecord models using Postgres + Rspec

Posted: 26 Oct 2016 07:31 AM PDT

I'm trying to test some models in a gem using Rspec and Postgres. Currently trying to do this by running a rake task in the spec_helper.rb file that will establish the pg database connection for the duration of my Rspec tests.

I've scanned other questions (my approach is largely based on these two questions 1, 2) and haven't discovered a good solution.

I'm not using the sqlite in-memory db feature due to the way our code is written.

Custom spec_helper looks like this:

RSpec.configure do |config|    load "support/schema.rb"    load File.expand_path("../../../lib/tasks/database.rake", __FILE__)    require File.dirname(__FILE__) + 'support/models.rb'    Rake::Task['database'].invoke  

However when I run rspec it tells me that there is no connection pool:

active_record/connection_adapters/abstract/connection_pool.rb:570:in  `retrieve_connection': No connection pool for ActiveRecord::Base  (ActiveRecord::ConnectionNotEstablished)  

Does anyone have any advice or insight on this issue? It would be much appreciated.

why id changed to _id when I use rails cache to get data

Posted: 26 Oct 2016 06:59 AM PDT

I'm using Rails with grape and Mongo, I wanna use Rails cache to optimize performance, and this is my code:

Rails.cache.fetch(cache_key, expires_in: 1.hour) do      render_template('chatrooms/info', {chatroom: chatroom, user:current_user, group: chatroom.group})  end  

the cache is valid, but the return data changed.

add cache before, return data is:

chatroom: {     name: "磁场",     id: "573c025cc5ffa353c7000000",     owner_id: "56a8b4c9feec620985000000",     avatar: "http://o2zuoh5os.qnssl.com/icon_magnet.png"  }  

otherwise, after adding cache, return data is:

chatroom: {     name: "磁场",     _id: "573c025cc5ffa353c7000000",     owner_id: "56a8b4c9feec620985000000",     avatar: "http://o2zuoh5os.qnssl.com/icon_magnet.png"  }  

the 'id' field changed to '_id'

I don't know what happened, how to resolve this issue?

Search Multi models on ruby rails

Posted: 26 Oct 2016 07:12 AM PDT

As a still beginner in to ruby rails and I'm trying to create a simple search option to website that I'm devolving

I have number of models

such as Sundries, Curry and Starter. my search work fine if I have a one model but how do I search all models title or name ?

I have added following command to each models and tried to display results in home page. but no luck!

def self.search(search)  where("LOWER(title) LIKE ?", "%#{search.downcase}%")   #where("content LIKE ?", "%#{search}%")  end  

Can someone please help me that with a example please?

Thank you.

Enable SSL on Ruby on Rails app with Nginx and Puma

Posted: 26 Oct 2016 07:21 AM PDT

Here is my Nginx conf file:

upstream app {    server unix:/home/deploy/example_app/shared/tmp/sockets/puma.sock fail_timeout=0;  }    server {      listen 80;    listen 443 ssl;    # ssl on;    server_name localhost example.com www.example.com;      root /home/deploy/example_app/current/public;      ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;      try_files $uri/index.html $uri @app;      location / {      proxy_set_header X-Forwarded-Proto $scheme;      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header X-Real-IP $remote_addr;      proxy_set_header Host $host;      proxy_redirect off;      proxy_http_version 1.1;      proxy_set_header Connection '';      proxy_pass http://app;    }      location /.well-known { allow all; }      location ~ ^/(assets|fonts|system)/|favicon.ico|robots.txt {      gzip_static on;      expires max;      add_header Cache-Control public;    }      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }  

The path to certificates are correct but when I access https://example.com it stay loading forever.

Is there any problem with my SSL setup?

Rails deep and advanced features [on hold]

Posted: 26 Oct 2016 06:30 AM PDT

I wish to get deep into Rails Framework with Ruby language, I stared with some simple book about Ruby language and is enough, but now I want to learn the advanced feature of rails framework, how middleware works, how memory is managed, threads, complexity, racks etc. and, apologize me, not the "stupid" MVC aspects like "Put views here, controllers here. models here and everythings will work". I want to understand why this and that.

So, not a text to build app faster but to understand framework's principles.

Any books?

Thank you.

Upload images into S3 bucket with ruby?

Posted: 26 Oct 2016 06:33 AM PDT

I able to upload to the bucket like this

s3 = Aws::S3::Resource.new

s3.bucket(bucket).object(fileName).upload_file(path)

but I want to upload the file into a folder inside the bucket?

Searching nested associations in Rails?

Posted: 26 Oct 2016 06:54 AM PDT

I have the following hierarchy of models:

  • At the top, there are Users.

    • Each user model has one ContactInfo
      • ContactInfo has one or more phones, emails, etc.
        • Each Phone has a label, and the phone. Likewise for each Email.
  • Users are connected to other users, and each connection is put in a group, such as work, family, etc.

    • Each connection has a ContactGroup, and the ContactInfo of another user.

So e.g, if Bob is connected to Jane, and Jane is in his Friends contact group, then it will look like this:

  • Bob:
    • Connections:
      • Group: Friends
      • ContactInfo:
        • User: Jane
        • Phones:
          • Label: Cell
          • Phone: +12345

My question is, how would I find all of Bob's contacts which have the phone +12345? This would need to search: user -> connections -> contactDetails -> phones -> phone

Ideally this should be a scope on the user model, but it can also be a method.

Any ideas?

Heroku - custom domain DNS

Posted: 26 Oct 2016 06:07 AM PDT

I am a complete newbie when it comes to redirecting etc.

I bought a domain (mydomain.co) and I have a heroku app (mydomain.herokuapp.com) (upgrading to paid in the upcoming month). What I want to do is to be able to access the heroku app after entering the domain url and stay o this domain, and not be redirected to mydomain.herokuapp.com.

My settings for the domain look like this (I translated it myself, so there may be some mistakes):

enter image description here enter image description here

With this settings, I can access my app but it is displayed in a frame, what's more - some of the pages do not work.

What I want to do is to be able to type mydomain.co and display mydomain.herokuapp.com but as regular site, and not inside a frame. What options should I choose?

Another thing is - will I be able to use the domain (which I paid for) and do the redirect if I do not buy a hosting from the company?

PS I added custom domains to my herokuapp and read their [guide], but I still do not understand.3.

Here are also my domain records - I believe it has something to do with this, but it so hard to test it as those DNS changes take some time.

enter image description here

Issue regarding ExecJS in rails 5

Posted: 26 Oct 2016 05:23 AM PDT

I am using rails 5 and I am using the following tutorial to generate an app for real time notification using action cable.

The link of the tutorial is :

http://myprogrammingblog.com/2016/08/22/rails5-actioncable-realtime-notifications-part3/

Now the source code is available here:

https://github.com/myprogrammingblog/notificator-rails5-example

Now after cloning it and running bundle install and all other necessary migrations,when I am going to start the application then the following error message is being prompted. It is bit weird and I did not get any valid reasoning yet.

The error is:

ExecJS::ProgramError in Notification#index

Showing C:/Ruby22/rails/notificator-rails5-example/app/views/notifications/_counter.html.erb where line #2 raised:

TypeError: Object doesn't support this property or method

where the corresponding code section is :

<li>    <%= image_tag("bell.png") %>    <span  id="notification-counter"><%= counter %></span>  </li>  

bell.png is placed under the assets/images folder and it looks like everything is fine.

Please help me to figure out this.

Thanks in advance!

PG::UndefinedTable: ERROR: relation does not exist for Multitenant Rails App

Posted: 26 Oct 2016 05:49 AM PDT

I am working on a Multi-tenant Ruby on Rails App along with another developer. I pulled his branch and received new migration files. I ran rake db:migrate. I visit the index of that controller and I get the undefined error.

After some research I understood that I ran migration after I created my Tenant. (Reference: PG::UndefinedTable: ERROR: relation "..." does not exist) and I also understand that rake db:reset resolved this issue in development. But doing a reset purges my data which I am fine with in development.

My concern is, how does this work in production? When I release to production... does that mean that for existing tenants I cannot run migrations and ship new features?

Is there a permanent solution to this?

Google API Key for Rails App for shorten url

Posted: 26 Oct 2016 05:19 AM PDT

I am trying to use the Google Api key to generate the shorten url for the rails app.

Can any one help how to use the keys to achieve it.

Excel to pdf conversion in rails4 with libreoffice

Posted: 26 Oct 2016 05:19 AM PDT

In a rails 4 application, how can I convert an excel spreadsheet file into pdf.

When I am trying to implement Excel to pdf the contents are listed in different pages if excel column size is large.

How to generate the pdf without moving data to next pages in pdf.

Please help, Thanks

Testing Devise Using capybara rspec and factory girl

Posted: 26 Oct 2016 05:01 AM PDT

i'm new at rails and i'm testing my devise gem User with capybara rspec and factory girl.

Here's spec code:

require 'rails_helper'  RSpec.describe User, type: :request do    it "displays the user's email after successful login" do      user = FactoryGirl.create(:user, email: 'test@test.com', password: 'password')      visit root_url      fill_in 'Email', with: 'test@test.com'      fill_in 'Password', with: 'password'      click_button 'Log in'      expect page.has_content?('jdoe')    end  end  

The problem is in

expect page.has_content?('jdoe') No matter what i put instead 'jdoe' test works perfectly without any errors.

Here's factory:

FactoryGirl.define do    factory :user do      email 'test@test.com'      password 'password'      password_confirmation 'password'    end  end  

Maybe I missed something or going with a wrong way. How should I test here?

Ruby sub-oject with dynamics presence of fields

Posted: 26 Oct 2016 04:40 AM PDT

I quite new ruby (rails) developer and I need to interface a complex object behavior. I'll try to explain as much as I can.

I've an object A in which I would like to contains an array of entities(B) which have a boolean base and a type. If this boolean is true some other properties can be set (and input fields can be showed in dashboard).

I don't really want to create a separate object(B).

I know I could use Struct.new(..)but don't know if it's usable.

By the way the array of B entities could be initialized when creating A object depends on A params and B type.

So my questions are:

  • Is it better to use a separate object or a Struct.new(...)entities for B ?
  • How could I manage other B params depends on type?

I hope it's understandable.

Thanks

Difference beetwen install GEM and Copy and IMPORT the JS file

Posted: 26 Oct 2016 07:43 AM PDT

I have the desire to know the diference between copy the JS and SASS file and import in the application.js and application.css and install a GEM...

Specifically I would like to install select2, could there be any performance difference in the implementation of plugin or something?

syntax error, unexpected end-of-input, expecting keyword_end

Posted: 26 Oct 2016 04:27 AM PDT

I have really tried to find out where I haven't closed some code but it all seems right to me. What have I done? I have checked all of the code carefully and hope someone can solve this for me!!!

 <nav class="navbar navbar-default" role="navigation">    <div class="container">    <!-- Brand and toggle get grouped for better mobile display -->    <div class="navbar-header">      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">        <span class="sr-only">Toggle navigation</span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>      </button>      <%= link_to "Pinteresting", root_path, class: "navbar-brand" %>    </div>        <!-- Collect the nav links, forms, and other content for toggling -->    <div class="collapse navbar-collapse navbar-ex1-collapse">      <ul class="nav navbar-nav navbar-right">        <li><%= link_to "Home", root_path %></li>        <li><%= link_to "About", about_path %></li>        <% if user_signed_in? %>        <li><%= link_to "Account Settings", edit_user_registration_path %></li>         <li><%= link_to "Log out", destroy_user_session_path, method: :delete %></li>         <% else %>        <li><%= link_to "Sign in", new_user_session_path %></li>    </ul>        </div>    </div><!-- /.navbar-collapse -->    </nav>  

Implement "add to favorites"

Posted: 26 Oct 2016 03:57 AM PDT

I am creating an app where a user can favorite a room. I started with a has_and_belongs_to_many association. But then I just noticed that it is very tricky to implement a remove button with drestroy. So I decided to do it this time with a has_many through association. I have a users who should add rooms to favorite or wishlist. Unfortunately when I click on the favorite button I am getting this error:

enter image description here

What I am missing how can I make this work?

If you need further information just let me know. I have used this as a direction.

Implement "Add to favorites" in Rails 3 & 4

favorite_room.rb

class FavoriteRoom < ApplicationRecord      belongs_to :room      belongs_to :user  end  

room.rb

belongs_to :user  has_many :favorite_rooms    has_many :favorited_by, through: :favorite_rooms, source: :user  

user.rb

 has_many :rooms   has_many :favorite_rooms    has_many :favorites, through: :favorite_rooms, source: :room  

routes.rb

 resources :rooms do      put :favorite, on: :member   end  

rooms_controller.rb

before_action :set_room, only: [:show, :favorite]  ...  ...  def favorite      type = params[:type]      if type == "favorite"        current_user.favorites << @room        redirect_to wishlist_path, notice: 'You favorited #{@room.listing_name}'        elsif type == "unfavorite"        current_user.favorites.delete(@room)        redirect_to wishlist_path, notice: 'Unfavorited #{@room.listing_name}'        else        # Type missing, nothing happens        redirect_to wishlist_path, notice: 'Nothing happened.'      end  end    private  def set_room    @room = Room.find(params[:id])  end  

show.html.erb

<% if current_user %>    <%= link_to "favorite",   favorite_room_path(@room, type: "favorite"), method: :put %>    <%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %>  <% end %>  

create_favorite_rooms.rb (migration file)

class CreateFavoriteRooms < ActiveRecord::Migration[5.0]    def change      create_table :favorite_rooms do |t|        t.integer :room_id        t.integer :user_id          t.timestamps      end    end  end  

Accessing first element of array in rails

Posted: 26 Oct 2016 05:01 AM PDT

I am getting below json from backend.

{ drug:    {        "id": "580f323ee4b06ffee69041a1",      "direction": [          {              "direction": "test",              "discarded": false          }      ]    }  }  

I dont want direction as array. I want it as object so I wrote method drug_format to parse json

My ruby on rails code for parsing is as follows :

def drug_format drug  {    id: drug[:id],    direction: drug[:direction][0],  }  end  

Now when I am trying to run my code I am getting following error.

NoMethodError (undefined method `[]' for nil:NilClass):      app/controllers/drugs_controller.rb:280:in `drug_format'      app/controllers/drugs_controller.rb:15:in `block in index'      app/controllers/drugs_controller.rb:14:in `each'      app/controllers/drugs_controller.rb:14:in `index'  

What can be the issue?

Send_file does not down load the file

Posted: 26 Oct 2016 04:19 AM PDT

I have an application with Rails 3.2.22 and Ruby 2.2. I'm trying to implement the send_file in my application. My download action will be triggered from a button click.

<input type='button' id='btn_save_log' value="Save"/>  

corresponding Ajax call implementation with the click event is given below.

$("#btn_save_log").on('click', function () {      $.ajax({          url: "/A/B/save_trunk_logs?device_id="+DeviceId+"&trunk_name="+TrunkDeviceName      })  });  

Controller action code is given below

def save_trunk_logs     device_id = params['device_id']     trunk_name = params['trunk_name'] ||= "test"     data =""     file = "#{trunk_name}.txt"     trunk_logs = from the db it will be taken(active record)      File.open(file, "w+") do |aFile|        aFile.write("Trunk Name : #{trunk_name}\n")        aFile.write("*"*100)        aFile.write("\n")        aFile.write("Time Stamp"+"\t"+"Log Message\n")        trunk_logs.each do |msg|          data =format_log_messages msg          aFile.write("#{data}\n")        end      end     send_file file, :type => 'application/text; charset=UTF-8', :disposition => 'attachment'  end  

every time i hit this action by a button click it says file is sent. but does not download in the browser.

If i manually hit the route in the browser, file is getting downloaded.I want a button click to download the file. What i'm doing wrong.

any help :)

Ruby - Rails 4 - Pundit - Policy and authorization error for a route #index_fr?

Posted: 26 Oct 2016 03:15 AM PDT

Sorry, I didn't see another place to ask a question about Pundit... Thank you for your help.

I am working on a Ruby on rails API and I would like to create an url (.../api/v1/attractions/fr) list some information about one of my models. But I've got this error message from Pundit :

Pundit::AuthorizationNotPerformedError at /api/v1/attractions/fr Api::V1::AttractionsController

and this error for verify_authorized in the lib/pundit.rb file

def verify_authorized      raise AuthorizationNotPerformedError, self.class unless pundit_policy_authorized?  end  

This is my configuration :

# app/config/routes.rb    namespace :api, defaults: { format: :json } do      namespace :v1 do        resources :lines, only: [ :index, :show ] do          collection do            get '/fr', to: 'attractions#index_fr'          end        end     end  end    # app/controllers/api/v1/attractions_controller.rb    class Api::V1::AttractionsController < Api::V1::BaseController  skip_before_action :authenticate_user!      def index      @attractions = policy_scope(Attraction)      @attractions = Attraction.all    end      def index_fr      @attractions = policy_scope(Attraction)      @attractions = Attraction.all    end  end    # app/policies/application_policy.rb    class ApplicationPolicy    attr_reader :user, :record      def initialize(user, record)      @user = user      @record = record    end      def index?      false    end      def index_fr?      false    end      def create?      false    end      def new?      create?    end      def update?      false    end      def edit?      update?    end      def destroy?      false    end      def scope      Pundit.policy_scope!(user, record.class)    end      class Scope      attr_reader :user, :scope        def initialize(user, scope)        @user = user        @scope = scope      end        def resolve        scope      end    end  end  end  

Is it possible to test other applications like https://www.google.com using capybara in Rails?

Posted: 26 Oct 2016 03:48 AM PDT

I am new to write test case in Rails. Is it possible to write test cases to test other applications like https://www.google.com using capybara in Rails ?

Dynamically get records between two dates

Posted: 26 Oct 2016 04:06 AM PDT

I'm working on a project at the moment where I have a voting system and on the index page for the vote model I can see the average vote for the last week. However I'd like to be able to have the user be able to choose the date between which the rating is averaged. I'm not sure how to go about doing this.

Currently I have a view which shows @average which is defined as:

Vote.where(date: (Date.today - 7)..(Date.today)).average(:score)  

My initial though was to include a 'date range' attribute to the model and then have the average calculated from those dates, which is set by a form in the index view, but that seems like a lot of overhead for such a simple task.

Any help would be greatly appreciated.

Trying to use files from AWS in prawn, got 403 error. But in my view i can upload and download with no problems

Posted: 26 Oct 2016 02:50 AM PDT

I have my AWS S3 account, and it everything setted up so it works with my upload files (using carrierwave gem) and downloading it so i can show it using html code.

I am finding an issue once i want to generate a pdf using that same image( lets say image link from amazon S3).

CarrierWave.configure do |config|                     config.fog_credentials = {      provider:              'AWS',      :aws_access_key_id     => 'ACCESS_KEY',                      :aws_secret_access_key => 'SECRET_KEY',            region:                'eu-central-1',          }    config.fog_directory  = 'BUCKET_NAME'       config.fog_public     = true               config.fog_attributes = { 'Cache-Control' => "max-age=#{365.day.to_i}" }    config.storage = :fog  end  

The problem here is, and this is why i don't understand, why i can with no issue upload files, download then to show on my view, only in Prawn i get this error

OpenURI::HTTPError: 403 Forbidden  

if i change my image path to a open build like google's logo it works with no issue, so i am thinking that the problem is in the authorisation between prawn and AWS.

I have already tried using the direct link that i can see inspecting the image form my view, and using it. And i got the same error.

I have already tried using also this CarrierWave configure inside my prawn controller, no error messages besides the same ones, saying that it is Forbidden.

image open(@shop_logo.to_s) , :position => :right, :fit => [130,80]  

My question is, how can i do this? I actually don't want to download the image, save it on my server use it for prawn and then deleted. There should be another way of doing this, or can't i just make the session open and use the same link twice?

A little note: @shop_logo has the link where the imaged it stored in AWS, the real link.

RabbitMq(bunny): Rabbitmq deleting message from queue . acknowledgement not working

Posted: 26 Oct 2016 04:04 AM PDT

I am processing records from my rabbitMQ. in order to avoid loss of messages from rabbitMQ i am using rabbitMQ acknowledgment strategey. For testing purpose i have raises the exception just before the code where i gave acknowledgment back to the rabbitMQ. as per the code that i have written rabbitMQ should not delete the message from queue untile the line in my code i.e "c.ack(delivery_info.delivery_tag)" is executed. Below is my code

begin  MessageService.with_channel do |c|      queue = c.queue(QUEUE_NAME, :durable => true)    exchange = c.topic(TOPIC_NAME, :durable => true)    queue.bind(exchange, :routing_key => "#{ROUTING_KEY_PREFIX}.#")    available_messages = queue.message_count    processed_messages = 0    fact_object = {}    while queue.message_count > 0 && processed_messages <= message_limit      queue.pop(:manual_ack => true) do |delivery_info, properties, payload|        rad_exam_hash_object = JSON.parse(payload)        entity_manager,criteria = self.query_revenue_cost_calculation(rad_exam_hash_object)        fact_object = self.revenue_cost_calculation_result(entity_manager,criteria)        self.insert_data_into_table(fact_object)        raise "exception"        c.ack(delivery_info.delivery_tag)      end      processed_messages = processed_messages + 1      available_messages = processed_messages - 1    end    [processed_messages, available_messages,fact_object]  end  rescue    puts "got exception while processing messages"  end  

Please help me in undestnding why rabbitMQ is deleting message from queue even if the line "c.ack(delivery_info.delivery_tag)" is not executed.

Function draws Error with Postgres Databse but not on Sqlite

Posted: 26 Oct 2016 06:41 AM PDT

So after shifting my code to heroku which is in Postgres one of my functions is drawing an error.

def index      @tutor = Tutor.where(:admin => false)      @tutor_array = []        @tutor_array << @tutor.fees_search(params[:fees_search]) if params[:fees_search].present?      @tutor_array << @tutor.subject_search(params[:subject_search]) if params[:subject_search].present?      @tutor_array << @tutor.lssubject_search(params[:lssubject_search]) if params[:lssubject_search].present?      @tutor_array << @tutor.ussubject_search(params[:ussubject_search]) if params[:ussubject_search].present?      @tutor_array << @tutor.jcsubject_search(params[:jcsubject_search]) if params[:jcsubject_search].present?        @tutor_array.each do |tutor|        ids = @tutor.merge(tutor).map(&:id)        @tutor = Tutor.where(id: ids)      end      @tutor = @tutor.sort_by { |tutor| tutor.rating.rating }.reverse      @tutor = @tutor.paginate(:page => params[:page], :per_page => 2)  end  

The particular line that gets highlighted is this ids = @tutor.merge(tutor).map(&:id)

I have read that certain calls works with sqlite and not with postgres such as doing LIKE ? and such. But i am pretty clueless as to whats wrong here.

Here's the error that is coming up

ActiveRecord::StatementInvalid in TutorsController#index

PG::UndefinedFunction: ERROR: operator does not exist: integer = character varying LINE 1: ...M "tutors" INNER JOIN "profiles" ON "tutors"."id" = "profile... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT "tutors".* FROM "tutors" INNER JOIN "profiles" ON "tutors"."id" = "profiles"."tutor_id" INNER JOIN "profile_ussubjects" ON "profiles"."id" = "profile_ussubjects"."profile_id" WHERE "tutors"."admin" = $1 AND "profile_ussubjects"."ussubject_id" = $2

I don't know what to search to try and resolve this since i dont even know what is it about postgres that is triggering the error.

So hopefully someone can point me in the right direction.

Here's what the tutor model looks like

def self.fees_search(n)      @profile = Profile.fees(n)      if @profile.empty?        return Tutor.none      else        @profile.map do |y|          y.tutor        end      end    end      def self.subject_search(s)      @subject = Subject.find_by_name(s)      unless @subject.nil?        @subject.tutors       end    end  

The other subject searches are all the same as self.subject_search.

I think one of the problems i have deduced would be this, in my self.subject_search(s) method, by testing it in the rails console, the line @subject.tutors is drawing the error.

In my rails console i ran subject = Subject.find_by_name("English") followed by subject.tutors and it threw the error

ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer = character varying  LINE 1: ...M "tutors" INNER JOIN "profiles" ON "tutors"."id" = "profile...                                                               ^  HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.  

Why though? Im sorry but im really quite bad with postgres and i dont understand whats going on and why it worked with sqlite3. (I read that sqlite3 is not as strict as postgres but that doesn't exactly make it clear for me)

rails eager_load from multiple association with different condition

Posted: 26 Oct 2016 02:16 AM PDT

complex_participators = participators.eager_load(:activities).where("archieved = ? AND pattern = ?", true, 'match')    complex_participators = participators.eager_load(:free_times).where(activity_id: id).order("participators.id ASC, free_times.start ASC")    complex_participators.each {|p| ...}  

I want a complex_participators array, each p have activities objects and free_times objects loaded

How can I do this?

No comments:

Post a Comment