Thursday, April 21, 2016

Rails 4.2 Clickable simple_calendar doesn't work on the other date than the current date | Fixed issues

Rails 4.2 Clickable simple_calendar doesn't work on the other date than the current date | Fixed issues


Rails 4.2 Clickable simple_calendar doesn't work on the other date than the current date

Posted: 21 Apr 2016 06:47 AM PDT

Good day guys. I am new to rails, currently building a clickable calendar with simple calendar gem for booking purpose, that I can click on certain date on the calendar, it will pass the date to my new_booking_path. I went through this post --> Rails 4 x simple_calendar gem: create new record on click in calendar cell and the function only works for the date shown when you first load the page. What's going on? Following are part of my codes.

In my index page:

<%= month_calendar do |day| %>    <%= content_tag :div, class: "calendar-day", data: {date: day} do %>      <%= day %>    <% end %>  <% end %>  

bookings_controller.rb

def new    @booking = Booking.new params[:booking] ? booking_params : {}  end  

Please help, thanks!!

Should I test associations between models?

Posted: 21 Apr 2016 06:42 AM PDT

Should I write a test for an association between two models?

I just found this code in one of my first Rails projects and this doesn't seem correct as not having the association causes an error rather than a failure. So how and where would I test them correctly?

require 'test_helper'    class VocabTest < ActiveSupport::TestCase      test "Must have 'belongs_to user' association" do      assert @vocab.user    end  end  

Run rails application On Azure VM

Posted: 21 Apr 2016 06:24 AM PDT

Recently we've analized the idea of migrating from Heroku to Azure for the deployment of our application.

I've managed to set up the VM and the basic example they give of running a rails app and the server works fine and I can connect.

When trying to migrate our project and running the server (with rails s -b 0.0.0.0) from the Azure VM, this message is shown in the browser:

This site can't be reached

localhost refused to connect.

ERR_CONNECTION_REFUSED

The thing is, usually when running locally I connect to localhost:3000 (I just run rails s). If I try to run the server like that on the VM, I get:

This site can't be reached

domain.cloudapp.net refused to connect.

ERR_CONNECTION_REFUSED

Am I missing some configuration from the VM or maybe it is from my application?

how to override devise sign_up method

Posted: 21 Apr 2016 06:54 AM PDT

I want the thing like that, when a user is registered by an admin using the devise signup views, the user shouldn't be kept in the session. By default the devise keep the user in the session using the following method in the registration controller.

  def sign_up(resource_name, resource)      sign_in(resource_name, resource)    end  

Now, how I can override this method from my registration controller that is inherited from the devise registration controller?

My registration controller codes are like as

    class RegistrationsController < Devise::RegistrationsController        skip_before_filter :require_no_authentication        before_filter :check_admin, only: [:new, :create]        before_action :load_department          def new          super         end          def create          super         end          private        def sign_up_params          params.require(:user).permit :display_name, :staff_code, :u_id, :email,            :contract_type, :employee_type, :department_id, :department_role, :avatar        end          def check_admin          if !user_signed_in?            redirect_to root_url          else            if !current_user.is_admin?              redirect_to root_url            else              true            end          end        end          def load_department          @departments = Department.all.collect do |department|            [department.name, department.id]          end        end      end  

bad URI(is not URI?): only in production using ruby 2.3, rails 4.1.7 deploying on heroku

Posted: 21 Apr 2016 06:48 AM PDT

I tried to put in production my website. But when my URI is called by the app, I have the following message

bad URI(is not URI?):

When I'm running the app on localhost it's working but when I running the app on production it doesn't work at all.

How can I solve this problème, I already tried :

uri = URI.parse(URI.encode(url.strip)) and other variable of this tips.

Thanks for your help.

Heroku setup that would support 3-5 Million visitors per hour

Posted: 21 Apr 2016 05:45 AM PDT

A post on the Reddit front page will gather as many as 30 million to 50 million page views. All of that within 24 hours, and perhaps only within 10 to 12 hours.

So, there could be 3 to 5 million visitors per hour. Say 3.6 mil per hour, that's 1000 visitors/second.

Our website: ruby on rails + postgres app that allows user registration (devise) and renders a simple page with a YouTube video embed.

Assuming an unlimited budget, approximately what Heroku setup would be able to handle the traffic? What's the likely bottleneck (db connections? concurrent requests?)

For example:   10 standard 1x dynos + Standard 2 Postgres DB  or  2 performance M dynos + Premium 2 Postgres DB  

deploy rails app digital ocean server

Posted: 21 Apr 2016 05:38 AM PDT

I am bit new to rails but somehow I manage to make an rails app. Now I want to deploy it to Digital Ocean server. All I got is

1- complete ruby on rails app

2- IP for digital ocean

3- Username

4- Password

can someone tell me steps to deploy it and which tools to use?

(I used fireFTP and Filezella for changing in some existing apps, but not sure that they are useful here or not)

selecting distinct first by one field

Posted: 21 Apr 2016 07:01 AM PDT

I have a Work model with a video_id, a user_id and some other simple fields. I need to display the last 12 works on the page, but only take 1 per user. Currently I'm trying to do it like this:

 def self.latest_works_one_per_user(video_id=nil)     scope = self.includes(:user, :video)     scope = video_id ? scope.where(video_id: video_id) : scope.where.not(video_id: nil)     scope = scope.order(created_at: :desc)     user_ids = works = []     scope.each do |work|       next if user_ids.include? work.user_id       user_ids << work.user_id       works << work       break if works.size == 12     end     works   end  

But I'm damn sure there is a more elegant and faster way of doing it especially when the number of works gets bigger.

How can I create wrapper for the types in the simple_form gem?

Posted: 21 Apr 2016 05:09 AM PDT

I want to create a wrapper for my app, but html for different types should be different. So, I can write just

= simple_for_for @task, wrapper: :mine_special do |f|    = f.input :first_attr, type: :sring    = f.input :second_attr, type: :boolean  

so, my initializer will contain definitions for both string & boolean types:

config.wrappers :mine_special, types: [:boolean] do |b|    # configs here for check box  end    config.wrappers :mine_special, types: [:string] do |b|    # configs here for text field  end  

How can I do that?

Sendgrid returns SMTP-AUTH requested but missing user name

Posted: 21 Apr 2016 05:08 AM PDT

I am new to ruby on rails and I follow the book Learn-ruby-on-rails by Daniel Kehoe. I have set up my sengrid login details correctly on the Ubuntu enviroment. echo $ SENDGRID_USERNAME returns my username correctly.

However, I still get "SMTP-AUTH requested but missing user name" error when I submit the contact form. I have tried to hardcode the login details and I still get the same errors. my configuration settings i smtp.sendgrid.net on port 587 and I allow send mails in development.

Please what am I not doing right. Thanks a lot.

My user_mailer.rb is as shown:

class UserMailer < ActionMailer::Base  #default :from => "do-not-reply@example.com"    def contact_email(contact)      @contact = contact      mail( to: => Rails.application.secrets.owner_email, from: => @contact.email, subject: => "Website Visit")  end   

end

while the contacts_controller.rb is shown below:

class ContactsController < ApplicationController    def new       @contact = Contact.new    end    def create      @contact = Contact.new(secure_params)      if @contact.valid?         UserMailer.contact_email(@contact).deliver_now          #TODO send message          flash[:notice] = "Message sent from #{@contact.name}."          redirect_to root_path      else          render :new      end   end    private     def secure_params      params.require(:contact).permit(:name, :email, :content)  end  

end

Rails Won't Render My View

Posted: 21 Apr 2016 05:05 AM PDT

I'm running devise with custom views, and my login page was rendering perfectly before, but I just changed the name of the model from human to user, renamed the controller and the views, but it just refuses to render my view.

I don't get an error, my layout renders perfectly, but it doesn't yield the body for some reason.

Code

Here's my routes.rb for Users:

  ## devise controllers for users    devise_for :user, controllers: {      confirmations: 'user/confirmations',      passwords: 'user/passwords',      registrations: 'user/registrations',      sessions: 'user/sessions',      unlocks: 'user/unlocks',      # commenting the below because omniauth gem isn't installed      # omniauth_callbacks: 'user/omniauth_callbacks'    }, skip: [:sessions]    ## custom routes for users    as :user do      get 'login' => 'user/sessions#new', :as => :new_user_session      post 'login' => 'user/sessions#create', :as => :user_session      delete 'logout' => 'user/sessions#destroy', :as => :destroy_user_session      get 'register' => 'user/registrations#new', as: :register    end  

Here's my sessions_controller generated by devise:

class User::SessionsController < Devise::SessionsController    ...      # GET /resource/sign_in    def new      super    end    ...  end  

Here's my view:

<%= render layout: 'layouts/shared/left_logo_panel' do %>    <%= form_for(resource, html: {class: 'form'}, as: resource_name, url: session_path(resource_name)) do |f| %>      <div class="field form-group">        <%= f.label :email %><br />        <%= f.email_field :email, class:'form-control', autofocus: true %>      </div>        <div class="field form-group">        <%= f.label :password %><br />        <%= f.password_field :password, class:'form-control', autocomplete: "off" %>      </div>        <% if devise_mapping.rememberable? -%>        <div class="field form-group">          <%= f.check_box :remember_me %>          <%= f.label :remember_me %>        </div>      <% end -%>        <div class="actions">        <%= f.submit "Log in", class:'btn btn-default' %>      </div>    <% end %>    <%= render "devise/shared/links" %>  <% end %>  

Log

Started GET "/login" for 127.0.0.1 at 2016-04-21 04:48:13 -0700  Processing by User::SessionsController#new as HTML    Rendered devise/shared/_links.html.erb (5.8ms)    Rendered layouts/shared/_left_logo_panel.html.erb (9.4ms)    Rendered user/sessions/new.html.erb within layouts/application (9.8ms)    Rendered layouts/_shim.html.erb (0.0ms)    Rendered layouts/_header.html.erb (0.3ms)    Rendered layouts/_footer.html.erb (0.0ms)    Rendered layouts/_ga.html.erb (0.1ms)  Completed 200 OK in 41ms (Views: 39.7ms | ActiveRecord: 0.0ms)  

Rails app on existing database encoding error

Posted: 21 Apr 2016 04:57 AM PDT

I'm making an app on existing database in firebird with charset windows-1250.
And im getting a lot of troubles because of this encoding.
In database.yml i got : encoding: windows-1250
In application.rb : config.encoding = "windows-1250"
In production.rb : Encoding.default_external = Encoding::UTF_8 Encoding.default_internal = Encoding::UTF_8
(if i dont have this I can't precompile my assets).
In layout/application.rb :
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250" />

All data from database are showing correct even with polish signs. But when i want to add polish signs to html files like layouts etc i get error:
ActionView::Template::Error (incompatible character encodings: Windows-1250 and UTF-8 So i need to use:
Iconv.conv('windows-1250', 'utf-8', 'xxx')

Is there any way to avoid this error and make my app to show polish signs correct?

Rails - Formats and Rendering - How do they work?

Posted: 21 Apr 2016 05:18 AM PDT

From what I understand, calling render will return a response to the browser. It can return different types of content (html, json, js,etc). I am however, a bit confused on what the browser does afterwards.

If the response is html, the browser just renders the page. If the response is json, usually, the client js code takes the json response and does something useful with it. If the response is js, what would the browser do? I am not sure if this js is appended to the document and executed? Is this related to Rails UJS?

Also, how is render related to respond_to? Are they used side by side, or is one preferred over the other?

render html:  render js:  render json:    respond_to |format| do    format.html    format.js    format.json  end  

Sorry if this may seem like a lot of questions, but I think it would help if these questions were discussed together.

Association among three model

Posted: 21 Apr 2016 04:52 AM PDT

I have these models with association as follows

class User    has_many :comments    belongs_to :country  end    class Country    has_many :users    has_many :comments  end    class Comment    belong_to :user    belong_to :country  end  

Comment has user_id and country_id as column name. User has country_id as column name.

Now if i write this code is console

User.first.comments.create :content=>"some content"  

This would create a comment but country_id column of Comment would be null. I want country_id to be filled based on user_id How can i do this

after_update callback won't update attribute

Posted: 21 Apr 2016 04:55 AM PDT

Good day... I have implemented an after_update callback for a specific column that will be updated, and after that column is updated the callback is meant to add the newly updated value to another column i.e

class Product < ActiveRecord::Base  after_update :update_stock, :if => :produced_changed?    private     def update_stock      self.stock = self.stock + self.produced   end       end  

When i run rails console and run "Product.update produced:450" the stock column will automatically add the new value. i.e it works perfectly but when I try updating from the "view/controller" it doesn't work at all.

please is there a reason why?

2.2.4 :004 > h => Product id: 1, name: "MAC Air Filter", partnumber: 33440, description: "Air filter", stock: 3440, created_at: "2016-04-08 11:38:58", updated_at: "2016-04-19 20:33:00", produced: 33

2.2.4 :006 > h.update produced:3000 (0.1ms) SAVEPOINT active_record_1 SQL (1.4ms) UPDATE "products" SET "produced" = ?, "updated_at" = ? WHERE "products"."id" = ? [["produced", 3000], ["updated_at", "2016-04-20 13:57:59.377954"], ["id", 1]] (0.1ms) RELEASE SAVEPOINT active_record_1 => true

2.2.4 :007 > h => Product id: 1, name: "MAC Air Filter", partnumber: 33440, description: "Air filter", stock: 6440, created_at: "2016-04-08 11:38:58", updated_at: "2016-04-20 13:57:59", produced: 3000>

vk sharing dollar sign

Posted: 21 Apr 2016 04:36 AM PDT

I have vk sharing button in my rails app it works great but one tiny problem with $ sign

my js

 javascript:          document.write(VK.Share.button({            url: "#{request.original_url}",            title: "#{@product.title}",            description: "#{@product.seo_description}",            image: "#{image_path @product.photos.first.image.url}",            noparse: true},            {type:'custom',            text: "<i class='icon-vk'></i>"}          ));  

On preview screen it looks like raw html code &#036; enter image description here Any idea how to fix it? screen

Update attribute from other model

Posted: 21 Apr 2016 04:45 AM PDT

I'm creating an app in Ruby on Rails to store played football games.

Each user has to join or create a league to keep the scoreboard private between friends.

When creating a league I want the creator to autojoin the created league.

Controller:

class LeaguesController < ApplicationController      before_action :authenticate_user!         def index           @leagues = League.all        end        def new          @league = League.new            @user = User.new      end        def show            @users = User.where(:league_id => current_user.league_id)            find_league        end        def create            @league = League.new(league_params)              @league.league_admin_id = current_user.id            find_user              update_attribute(:user, @league.id)            @user.save(user_params)            if @league.save                redirect_to root_path, :notice => "Successfully created a league"          else              render 'index'          end      end        def edit          find_league      end        def update          find_league            if @leagues.update(league_params)                redirect_to @leagues, :notice => "Successfully editted this league!"          else              render 'edit'          end  end          private      def find_league          @leagues = League.find(params[:id])          end        def find_user          user = User.find(current_user)          end        def league_params          params.require(:league).permit(:league_name, :league_admin_id, :join_key, :league_rules)      end        def user_params          params.require(:user).permit(:league_id)      end        end   

So in the create action I'm looking for the current_user trough the private method find_user, then I'm updating the field league_id and then I'm saving this value. However when creating a new league the autojoin didn't work. What am I doing wrong here?

How to show the accumulative push notification instead of showing multiple notifications that tend to appear at the same time?

Posted: 21 Apr 2016 04:52 AM PDT

Whenever a new event is added, a push notification is sent to the user. If ten events are added in row, ten push notifications will be sent to the user, a behavior that will be annoying.

I'd like to have it like this: if ten events are added in row, or added very near to each other regarding time, only one push notification will be sent to each user, saying: "#{event.name} and 19 others events added that match your interests.".

Here's what I've done so far:

Added a field last_sent_notification in users table. Each time a new event is added, it is checked that the created event isn't in the 2 minutes radius of last_sent_notification, and a notification is fired.

If a new created event is in the 2 minutes radius of last_sent_notification, a background job is created, that will wait for 2 minutes for any other upcoming event, and will fire after 2 minutes. If a new event is created while the 2-minute-wait, the notification will take into account all the events created during that 2-minute-wait.

The only disadvantage to this problem is: as an event is added, the notification won't be sent right away. There will be a delay of 2 minutes.

Is there any design patter or optimum solution that could better do this job?

Moving servers effect my SEO

Posted: 21 Apr 2016 04:35 AM PDT

Just a question our old website is on Ruby on Rails with another server than Go Daddy (Domain is with go daddy), i rewrote the application in php and would like to move this back to go daddy will this effect my SEO ?.

Is there a PG issue with multiple AJAX submissions in a Rails Rspec test?

Posted: 21 Apr 2016 04:22 AM PDT

I'm running integration tests on my Rails app using a PG database, Rspec, Capybara and the poltergeist gem for javascript submissions. Essentially I'm testing the flow/presentation of questions in a question tree - and in my rspec tests I click and answer, submit via AJAX, then test that the correct next_question is appearing. This works fine when testing 1/2 questions deep, but once I start submitting >3 questions in series using JS, I get the following error:

 PG::Error:     result has been cleared  

I'm also seeing:

Failure/Error: let(:user) { FactoryGirl.create(:user, password: 'Foobar') }   ActiveRecord::RecordInvalid:     Validation failed: Email has already been taken  

Errors like this crop up, which don't if I remove the offending deep js submissions.

Here's the code that fails:

    describe 'the Sales Opportunity access to Sale Qualifiers view', :type => :feature do      let(:user) { FactoryGirl.create(:user, password: 'Foobar') }      let(:company) { FactoryGirl.create(:company, organization: user.organization)}      let(:sales_opportunity) { FactoryGirl.create(:sales_opportunity, company: company, user: user) }      let(:sale_qualifier) { FactoryGirl.create(:sale_qualifier, sales_opportunity: sales_opportunity) }      let(:answer) { sale_qualifier.create_answer(answer_text: 'I am the answer to question 1')}          before(:each) do         sign_in user         visit sales_opportunity_path(sales_opportunity)     end        it 'tests submitting more than one question answer', js: true do       within('#qualifier_tabs') do        page.click_link('Fit')        sleep 1        end        within('#qualifier_panel') do          expect(page).to have_content('Has the company released formal requirements to demonstrate against, or an RFI or RFP?')          page.select('Yes', from: 'sale_qualifier_answer_attributes_answer_text')          page.click_button('Submit')          sleep 1          expect(page).to have_content('Briefly describe the most important requirements')          expect(page).to have_selector('textarea#sale_qualifier_answer_attributes_answer_text')          page.fill_in('sale_qualifier_answer_attributes_answer_text', with: "some important requirements")          page.click_button('Submit')          sleep 1          expect(page).to have_content('How well do your products or services match these requirements?')          expect(page).to have_selector('select#sale_qualifier_answer_attributes_answer_text')          page.select('Good fit', from: 'sale_qualifier_answer_attributes_answer_text')          page.click_button('Submit')        end    end  

Is this caused by the number of AJAX submissions in series? If so, how would I test this (at first glance it seems I can test the submit button, but I'd need to build a series of answers in FactoryGirl and then test the view rather than using js: true AJAX submissions.

Parsing a string of varying nested data structures

Posted: 21 Apr 2016 05:55 AM PDT

I have a method that parses a string value and converts it into a selected data type, but I am having difficulty converting strings with nested data structures, eg:

"[1,2,3,{'hello' => 'world'}]"  

Currently I convert using the eval method but this causes a massive security issue because the string is actually input by a user.

Is there a different way in which I can parse these types of string? I have tried JSON.parse but it doesn't like the nested hash inside of the array.

Image upload using carrierwave in show page

Posted: 21 Apr 2016 04:10 AM PDT

Using Rails 4 and Ruby 2.2,

I have book as model which should have image upload functionality in the show page of book. So User can create the book first and from show page upload the multiple images for book. I have used carrierwave as gem and have separate model created for Image.

image.rb

class Image < ActiveRecord::Base    belongs_to :book      mount_uploader :avatar, AvatarUploader  end  

book.rb

class Book < ActiveRecord::Base      belongs_to :subject, dependent: :destroy      belongs_to :user, dependent: :destroy      has_many :images, dependent: :destroy  end  

books/show.html.erb

<%= form_for(Image.new, :html => { :multipart => true }) do |f| %>     <div class="field">       <%= f.label :name %><br>       <%= f.text_field :name %>       <%= hidden_field_tag "image[book_id]", @book.id %>     </div>     <%= f.fields_for :images do |p| %>       <div class="field">         <%= p.label :avatar %><br>         <%= p.file_field :avatar, :multiple => true, name: "images[avatar]" %>       </div>     <%end%>       <div class="actions">       <%= f.submit %>     </div>  <% end %>  

schema.rb

  create_table "images", force: :cascade do |t|      t.datetime "avatar_updated_at"      t.datetime "created_at",                    null: false      t.datetime "updated_at",                    null: false      t.integer  "book_id",           limit: 4      t.string   "avatar",            limit: 255      t.string   "name",              limit: 255    end      create_table "books", force: :cascade do |t|      t.string   "title",       limit: 255      t.integer  "page_number", limit: 4      t.text     "description", limit: 65535      t.datetime "created_at",                                null: false      t.datetime "updated_at",                                null: false      t.integer  "user_id",     limit: 4      t.integer  "subject_id",  limit: 4      t.boolean  "active",                    default: false    end  

Now I am kind of unable to proceed with this, can someone guide me on this because I am having form in books/show page and I need to show the image on the same page after successful updation of images.(Multiple images can be uploaded)

Thanks in advance

let me know if I need to provide any more information.

Neither PUB key nor PRIV key: nested asn1 erro

Posted: 21 Apr 2016 04:33 AM PDT

I am getting An OpenSSL::PKey::RSAError Neither PUB key nor PRIV key: nested asn1 error while integrating paypal gateway. Here is my code:

gw=:paypal_express   paypal_options=YAML.load_file(Rails.root.join('config', 'paypal.yml'))[Rails.env]   paypal_options[:pem]=File.read("#{Rails.root}/paypal_cert_pem.txt")     gateway=ActiveMerchant::Billing::Base.gateway(gw).new(paypal_options)    gateway.set‌​up_purchase(200,:return_url => "xyz",:cancel_return_url => "xyz",:description => "Working good")  

Active record for sql

Posted: 21 Apr 2016 04:22 AM PDT

Please help i need ruby active record query for this sql:

SELECT `properties`.* FROM `properties` INNER JOIN `recentviews` ON `recentviews`.`property_id` = `properties`.`id` WHERE `recentviews`.`user_id` = 2 ORDER BY `recentviews`.`view_time` DESC  

Create device fingerprint for Ios - Rails

Posted: 21 Apr 2016 03:44 AM PDT

Have to create a Fingerprint for Ios Device.

I have used,

gem 'fingerprintjs-rails'  

It is generating fingerprint based on brower. But i need fingerprint only based on device data not based on browser

Is there any other way to do it.

mariadb with rails: can't install libmysqlclient-dev

Posted: 21 Apr 2016 03:39 AM PDT

I have mariadb-10.1 installed on a stock 64bit Ubuntu 15:10.

I have libmysqlclient18 succesfully installed, but I get errors when trying to install libmysqlclient-dev.

steve@steve:~$ dpkg -s libmysqlclient18  Package: libmysqlclient18  Status: install ok installed  Priority: optional  Section: libs  Installed-Size: 10  Maintainer: MariaDB Developers <maria-developers@lists.launchpad.net>  Architecture: amd64  Source: mariadb-10.1  Version: 10.1.13+maria-1~wily  Replaces: libmysqlclient18 (<< 10.1.13+maria-1~wily)  Depends: libmariadbclient18 (= 10.1.13+maria-1~wily)  Description: Virtual package to satisfy external depends   This is an empty package that provides an updated "best" version of   libmysqlclient18 that does not conflict with the libmariadbclient18   package.   .   MariaDB is a fast, stable and true multi-user, multi-threaded SQL database   server. SQL (Structured Query Language) is the most popular database query   language in the world. The main goals of MariaDB are speed, robustness and   ease of use.  Homepage: http://mariadb.org/  steve@steve:~$ sudo apt-get install libmysqlclient-dev  Reading package lists... Done  Building dependency tree         Reading state information... Done  Some packages could not be installed. This may mean that you have  requested an impossible situation or if you are using the unstable  distribution that some required packages have not yet been created  or been moved out of Incoming.  The following information may help to resolve the situation:    The following packages have unmet dependencies.   libmysqlclient-dev : Depends: libmysqlclient18 (= 5.6.28-0ubuntu0.15.10.1)                  but 10.1.13+maria-1~wily is to be installed  E: Unable to correct problems, you have held broken packages.  

Can anyone suggest how to resolve this?

Thanks :-)

Steve

Oracle TNS error with Ruby on Rails Rake command

Posted: 21 Apr 2016 06:24 AM PDT

I am trying to use the Ruby on Rails Rake command to migrate to an Oracle database. My database.yml file contains the following:

development:      adapter: oracle      database: album_development      sid: orc1                username: system      password: root  

On my PC I have set ORACLE_SID=orcl.

When I run Rake,migrate, I get the following error:

rake aborted!  The driver encountered an error: java.sql.SQLException: Listener refused the connection with the following error:  ORA-12505, TNS:listener does not currently know of SID given in connect descriptor  

Can you tell me if I need to modify my listener.ora file to get this to work? My listener.ora file is as follows:

SID_LIST_LISTENER =    (SID_LIST =      (SID_DESC =        (SID_NAME = PLSExtProc)        (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)        (PROGRAM = extproc)      )      (SID_DESC =        (SID_NAME = CLRExtProc)        (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)        (PROGRAM = extproc)      )    )    LISTENER =    (DESCRIPTION_LIST =      (DESCRIPTION =        (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))        (ADDRESS = (PROTOCOL = TCP)(HOST = Lenovo-PC)(PORT = 1521))      )    )    DEFAULT_SERVICE_LISTENER = (XE)  

The output of the lsnrctl Status command is as follows:

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))  STATUS of the LISTENER  ------------------------  Alias                     LISTENER  Version                   TNSLSNR for 32-bit Windows: Version 11.2.0.2.0 - Production  Start Date                21-APR-2016 11:14:15  Uptime                    0 days 0 hr. 7 min. 43 sec  Trace Level               off  Security                  ON: Local OS Authentication  SNMP                      OFF  Default Service           XE  Listener Parameter File   C:\oraclexe\app\oracle\product\11.2.0\server\network\admin\listener.ora  Listener Log File         C:\oraclexe\app\oracle\diag\tnslsnr\Lenovo-PC\listener\alert\log.xml  Listening Endpoints Summary...    (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1ipc)))    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=Lenovo-PC)(PORT=1521)))    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=Lenovo-PC)(PORT=8080))(Presentation=HTTP)(Session=RAW))  Services Summary...  Service "CLRExtProc" has 1 instance(s).    Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...  Service "PLSExtProc" has 1 instance(s).    Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...  Service "XEXDB" has 1 instance(s).    Instance "xe", status READY, has 1 handler(s) for this service...  Service "xe" has 1 instance(s).    Instance "xe", status READY, has 1 handler(s) for this service...  The command completed successfully  

Can anyone help / make a suggestion?

How in factorygirls create two objects Freelancer and User after creting object User, with id = user.id?

Posted: 21 Apr 2016 03:26 AM PDT

How in factorygirls create two objects Freelancer and User after creting object User, with id = user.id?

FactoryGirl.define do    sequence :email do |n|      "user#{n}@test.com"    end      sequence :username do |n|      "user#{n}"    end      sequence :id do |n|     n    end      factory :user do      id       username       email      password 'qwerty'      password_confirmation 'qwerty'        factory :user_with_freelancer do        after(:create) do |user|          create(:freelancer, user: user, id: user.id)          create(:photo, freelancer: freelancer, id: freelancer.id)          end      end    end      factory :freelancer do      end      factory :photo do      end    end  

In test I am calling:

given(:user) { create(:user_with_freelancer) }  

Freelancer is creating ok, but how create photo with id = user.id and photo belongs_to freelancer?

Rails and devise - testing controller when signed in and signed out

Posted: 21 Apr 2016 04:16 AM PDT

So I want to test controller which is using devise.

require 'rails_helper'    describe ArticlesController do    before(:all) { @article = FactoryGirl.create(:article) }      sign_in_admin      describe 'GET new' do      let(:call_request) { get :new }        before { call_request }        context 'admin signed in' do        it { is_expected.to respond_with :ok }      end        context 'admin signed out' do        it { is_expected.to respond_with 302 }      end    end  end  

I followed this guide from devise wiki. So I created ControllerMacros module as you can see here:

module ControllerMacros    def sign_in_admin      before(:each) do        @request.env['devise.mapping'] = Devise.mappings[:admin]        @admin = FactoryGirl.create(:admin)        sign_in @admin      end    end  end  

And included it, and other needed things to rails_helper:

require_relative 'support/controller_macros.rb'    RSpec.configure do |config|    config.include Devise::TestHelpers, type: :controller    config.extend ControllerMacros, type: :controller  (...)  

Here is admin factory:

FactoryGirl.define do    factory :admin do      email 'email@email.com'      password 'password'    end  end  

But now I don't know how to sign out admin? As sign_in_admin is executing before each test, but I need to sign admin out for some of the tests. What is the best way to test this controller with signed in/out admin?

btw I'm kinda new to testing

How to check if table is empty during metadata lock in mysql

Posted: 21 Apr 2016 03:09 AM PDT

I need to maintain ping service that has to check if particular table is empty every 20 seconds. However, from time to time a script performs work on that table which results in metadata lock. This script can sometimes run for hours. This results in ping requests falling into "waiting for metadata lock" state and piling up very fast. Sometimes this results in "too many connections" error.

My question is: is there a way to check if table is empty, that does not care if there is a lock? If not, what other solutions are possible?

I am using Rails 3.2 with RDS mysql.

No comments:

Post a Comment