Friday, April 29, 2016

How to nest namspaced resources and avoid double namespacing - uninitialized constant ActsAs::ActsAs | Fixed issues

How to nest namspaced resources and avoid double namespacing - uninitialized constant ActsAs::ActsAs | Fixed issues


How to nest namspaced resources and avoid double namespacing - uninitialized constant ActsAs::ActsAs

Posted: 29 Apr 2016 07:09 AM PDT

I have two namespaced models in a Rails app - ActsAs::Comments and ActsAs::Likes. Both are polymorphic, and belong to several different parent models. Improtantly for this question, Likes can belong to a Comment.

So my routes look something like this

namespace :acts_as do    resources :comments do      namespace :acts_as do        resources :likes, only: :create      end    end  end   resource :other_objects do    namespace :acts_as do      resources :likes, only: :create    end  end  

I then have a shared partial, called in the parent object's view, for adding likes.

<%= link_to 'Like',     polymorphic_path(       [ @object, ActsAs::Like.new ],       like: { likable_type: @object.class.name, likable_id: @object.id }     ) %>  

This work's fine for OtherObjects, but not for Comments.

Rake routes shows

acts_as_comment_acts_as_likes    POST       /acts_as/comments/:comment_id/acts_as/likes(.:format)  acts_as/acts_as/likes#create  # note the double namespacing of the controller  

Clicking 'like' gives

ActionController::RoutingError - uninitialized constant ActsAs::ActsAs:  

What is the correct way to set this up and avoid this double namespacing of the controller?

Running rails project on heroku

Posted: 29 Apr 2016 07:13 AM PDT

I a little bit new for heroku and postgresql and dont know how works translting from mysql to postgresql. My application was developed on mysql and to run it from heroku i made some steps: 1. Added a gem 'pg' and gem 'rails_12factor' like that:

group :production do    gem 'pg'    gem 'rails_12factor'  end  

And bundle it without production 2. I also changed my database.yml into: (Also i have question, how can i use mysql in devolepment and postgre in production?)

# PostgreSQL. Versions 8.2 and up are supported.  #  # Install the pg driver:  #   gem install pg  # On OS X with Homebrew:  #   gem install pg -- --with-pg-config=/usr/local/bin/pg_config  # On OS X with MacPorts:  #   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config  # On Windows:  #   gem install pg  #       Choose the win32 build.  #       Install PostgreSQL and put its /bin directory on your path.  #  # Configure Using Gemfile  # gem 'pg'  #  default: &default    adapter: postgresql    encoding: unicode    # For details on connection pooling, see rails configuration guide    # http://guides.rubyonrails.org/configuring.html#database-pooling    pool: 5  

But! When i tryed to work via heroku(downloading works fine) my dynamic pages wasnt working, and i get this errors: Errors

So, i guessed that DB just doesnt migrate, OK, i runned via console this: heroku run rake db:migrate --app name
Aaand i now i have this error:

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "schoolings" does not exist  : ALTER TABLE "students" ADD CONSTRAINT "fk_rails_e33c769d03"  FOREIGN KEY ("schooling_id")  REFERENCES "schoolings" ("id")   

My questions:

1. Why it happens? Did i miss some steps when deployed my app?

2. How can i separate production and dev DB in deployment.yml?

Thanks, for any help!

comparing one element in an ActiveRecord array to all others ruby on rails

Posted: 29 Apr 2016 07:00 AM PDT

I have a simple ActiveRecord query along the lines of this:

similar_changes = Notification.where(change_owner: 'foo1', change_target: 'foo2', change_cancelled: false)  

Each notification object has a field change_type and I have another function that checks one Notification's change_type with one other Notification for inverse changes (changes that undo each other in the context of my application)

I need to take this Notification's change_type and compare it against all others in the array. I have to reference the objects like so: similar_changes[0]['change_type'] where the first index is each ActiveRecord in the array and the second is the dictionary that specifies which property in the Notification object.

I have a feeling I could do this manually with two nested loops and if statements, but I also know Ruby and I feel like this is something that it should have built in.

Am I wrong, or is there a better way to do this?

For reference (if it matters) here is how I check for inverse changes:

def inverse?(possible_inverse_change)   is_inverse = false   change_types = YAML.load_file(File.join(NotificationManager::Engine.root, 'config/change_types.yaml'))   if self.change_type == change_type[possible_inverse_change]['inverse']    is_inverse = true   end   return is_inverse  end  

wkhtmltopdf not corresponding size after generating pdf Rails

Posted: 29 Apr 2016 06:49 AM PDT

Iv got a small problem using wkhtmltopdf (wicked_pdf) with rails.

This is my pdf after generating.

enter image description here

and this is my show action. respond_to do |format| format.html

  format.pdf do      render :pdf      => "resume",             :encoding => "utf-8",             :template => "resumes/show/#{template_id}",             #:orientation                    => 'Landscape',                 #:show_as_html                   => params[:debug].present?,             :disable_smart_shrinking        => true,             #:disable_javascript             => true,             :margin   => {:top => 5, :bottom => 5, :right => 5, :left => 5}    end  end  

As you can see this is an A4 size page (by default) and Im giving 5 mm margin on each side. The A4 paper have in width 210 mm. Now after Im giving margin of 5mm I'm left with 200mm right? OK

In css Im giving to this container a max width of 200mm + those 10 mm of margin should be 210 mm (the size of an A4 page)

.page-container{      background: white;      width: 200mm;      max-width: 200mm;      display: block;    }  

As you can see in the pic, the generated pdf has way way more mm in width then 210. Any ideas why and how to fix it?

If Im setting the width to 100% it will work but that doesnot mean that the width will be 210 mm.

Whitelist params - how to allow n level nesting of self relationship?

Posted: 29 Apr 2016 06:29 AM PDT

I've got a use case where employee hierarchies are going to be stored as strings so they can be retrieved in json. (This is a POC, so just a hack for SQLite for now).

How can I permit n level of nested objects? In the following example :h_data is json coming in the request body. Right now I'm hacking it to 3 levels of hierarchy with:

params.require(:hierarchy_version).permit(:name, :creator_id, :top_employee_id, :h_data => [:name, :id, :salary, :manager_id, :direct_reports => [:name, :id, :salary, :manager_id, :direct_reports => [:name, :id, :salary, :manager_id, :direct_reports]]])  

How to Encrypt data in ruby same as SecretKeySpec?

Posted: 29 Apr 2016 06:19 AM PDT

I am trying to encrypt a string in ruby using Cipher with AES algorithm. I have example written in Java. I have taken help from this example and written code in Java but not able to get the same output as in JAVA.

Following is the code written in java

import java.util.Base64;  import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.InputStream;  import java.io.InputStreamReader;  import java.net.URL;  import java.net.URLDecoder;  import java.net.URLEncoder;  import java.security.Key;  import java.security.KeyManagementException;  import java.security.NoSuchAlgorithmException;  import java.security.cert.X509Certificate;  import javax.crypto.Cipher;  import javax.crypto.spec.SecretKeySpec;  import javax.net.ssl.HostnameVerifier;  import javax.net.ssl.HttpsURLConnection;  import javax.net.ssl.SSLContext;  import java.util.Arrays;  import javax.net.ssl.SSLSession;  import javax.net.ssl.TrustManager;  import javax.net.ssl.X509TrustManager;    public class HelloWorld {      public static final String PHONENUMBER_PARAM = "phoneNumber";      public static final String PIN_PARAM ="pin";        public static final String MERCHANTID_PARAM = "merchantId";        public static void main(String args[]) throws Exception {        String phoneNumber ="+917738995286";      String pin ="5577";        String merchantId ="527425858";      String encodedKey ="vPDkdTDrcygLPROzd1829A==";        String payLoad = PHONENUMBER_PARAM + "=" +         URLEncoder.encode(phoneNumber, "UTF-8")+ "&" + PIN_PARAM + "=" + URLEncoder.encode(pin, "UTF-8") ;        byte[] decodedKey = Base64.getDecoder().decode(encodedKey.getBytes());        Key encryptionKey = new SecretKeySpec(decodedKey, "AES");        byte[] utf8Bytes = payLoad.getBytes("utf-8");        byte[] encryptedBody = encrypt(encryptionKey, utf8Bytes);      String encryptedData = new  String(Base64.getEncoder().encode(encryptedBody));        System.out.println("encryptedData:" + encryptedData);   }  private static byte[] encrypt(Key encryptionKey, byte[] data) throws Exception {      Cipher c = Cipher.getInstance("AES");      c.init(1, encryptionKey);      return c.doFinal(data);  }  }  

Output of this code is

encryptedData:lE40HlECbxU/mWRivF/+Szm3PprMoLW+Y7x911GczunakbG8l+A2JVEEP8gTw6xy

I tried to write the same code in ruby. Ruby Code is:

payLoad = "phoneNumber=%2B917738995286&pin=5577"    encodedKey = "vPDkdTDrcygLPROzd1829A=="    decodedKey = Base64.decode64(encodedKey)    dKey = decodedKey.each_byte.map { |b| b.to_s(16) }.join    cipher = OpenSSL::Cipher.new('aes128').encrypt  encryptionKey  = cipher.update(dKey)   encryptionKey<< cipher.final      utf8Bytes = payLoad.bytes  uKey = utf8Bytes.map { |b| b.to_s(16) }.join    scipher = OpenSSL::Cipher.new('aes128').encrypt  scipher.key = encryptionKey    encryptedBody = scipher.update(uKey)   encryptedBody<< scipher.final    encryptedData  = Base64.encode64(encryptedBody)  

Output of this code is

CqFmCKJ004PsoXi2tDCTBmx7/iTHVyDsFH9y8NWNrEP3k3bOQp7h8uyl/a7Z\nYi9ZmcXSspo6FCyCo6fJIwPohg==\n

Don't know where is the error. I have already worked for 2 days but not able to get any answer. Any help will be great. Thanks in advance.

ActiveJob with Resque plugins

Posted: 29 Apr 2016 06:10 AM PDT

Is there a way to use Resque plugins, such as resque-loner, with ActiveJob and Resque as backend for it?

Cant use class defined inside lib folder in rails app

Posted: 29 Apr 2016 07:13 AM PDT

I have created a class in my lib folder inside my rails app lib/pundit/current_context.rb :

class CurrentContext    attr_reader :user, :account_asso      def initialize(user, account_asso)      @user = user      @account_asso = account_asso    end  end  

This class is then called in my base_controller :

  def pundit_user      CurrentContext.new(current_user, account_asso)    end  

I am always getting :

NameError - uninitialized constant Api::V1::BaseController::CurrentContext:  

I thought it might be because I am not loading the files inside lib ? so I added config.autoload_paths << Rails.root.join('lib') inside my config/application.rb file :

require File.expand_path('../boot', __FILE__)    require "rails"  # Pick the frameworks you want:  require "active_model/railtie"  require "active_job/railtie"  require "active_record/railtie"  require "action_controller/railtie"  require "action_mailer/railtie"  require "action_view/railtie"  require "sprockets/railtie"  # require "rails/test_unit/railtie"    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module QuickBedApi    class Application < Rails::Application      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      # config.time_zone = 'Central Time (US & Canada)'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      # config.i18n.default_locale = :de      config.middleware.insert_before 0, "Rack::Cors" do        allow do          origins '*'          resource '*', :headers => :any, :methods => [:get, :post, :options]        end      end      # Do not swallow errors in after_commit/after_rollback callbacks.      config.active_record.raise_in_transactional_callbacks = true      config.autoload_paths << Rails.root.join('lib')    end    end  

Unfortunately I am still getting the error. How can I solve that ?

Capistrano deployment broken by new request for Capistrano-Harrow gem?

Posted: 29 Apr 2016 06:38 AM PDT

I thought my capistrano version was locked to 3.4.0, however it seems that it updated to 3.5. I tried going back to 3.4, but I keep getting the following message when I try to deploy my project to server.

    DEBUG [72bb6fc3]    An error occurred while installing capistrano-harrow (0.3.2), and Bundler cannot  continue.  Make sure that `gem install capistrano-harrow -v '0.3.2'` succeeds before  bundling.  

I'm not familiar with capistrano-harrow, but read a little and doesn't seem like something I need. I did add to my gemfile in hopes of getting the deployment to send but even though that seemed to install fine, it still errors out for deployment. When I try executing gem install capistrano-harrow -v '0.3.2' - I get the following message and it doesn't install.

ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)      bad response Not Found 404 (https://rubygems.global.ssl.fastly.net/quick/Marshal.4.8/capistrano-harrow-0.3.2.gemspec.rz)  

Anyone know how I can either, opt out of harrow to try and get my deploy to work, or correct this issue to move forward? Thanks!

Update

I ran the following command to "opt-out", however, it still needs to build/install the gem I suppose which is currently the real issue.

git config harrow.disabled true

How to get the records where status is equal to nil and not equal to privilage or casual

Posted: 29 Apr 2016 06:09 AM PDT

i have a leave table. in this i have a status column. which is a string column.i want to get those records from leave table where status column is equal to null and status not equal to privilage or casual or sick. how to write this query in rails 4 ?

leave.where(:status => nil).where.not(:status => "casual" or "privilage" or "sick").  

Rails date check if parsable

Posted: 29 Apr 2016 06:02 AM PDT

I have a datetime picker which sends the checkin & checkout dates with search box. Then the url looks like;

http://localhost:3000/locations/listings?utf8=%E2%9C%93&search=london&start_date=12%2F04%2F16&end_date=20%2F04%2F16  

and I take the params hash and parse the string,

start_date = Date.parse(params[:start_date])  end_date = Date.parse(params[:end_date])  

first of all, I have to check if (start_date.present? && end_date.present?) and that works fine.

But if the user manually types something else rather than the date to url such as;

http://localhost:3000/locations/listings?utf8=%E2%9C%93&search=london&start_date=londoneye6&end_date=20%2F04%2F16   

Then of course I get an error;

invalid date  

How should I control if the string is parsable on controller action. I should be also checking london-eye, london/eye strings, which include - /

Thank you

How can I verify username or email are correct using Devise and Rails 4

Posted: 29 Apr 2016 05:15 AM PDT

I am using Devise and Rails 4.

I am working with login screen. In login screen i'm passing username/email and password but I have to check whether any one of the field username or email matched with any user in system.

Tried following condition to find user with username or email but it will be throwing an error for devise valid password method.

Condition:

user = User.where(["username = :value OR email = :value", { :value => username.downcase }])  

after this i'm checking user password as like user.valid_password?(password)

Error: NoMethodError (undefined method `valid_password?' for #)

For following condition valid_password? will be working fine

user = User.find_by(email: email.downcase)  

But i have to check both username and password in ::find_by method like as follows

user = User.find_by("email= email.downcase OR username= email.downcase")  

Is there some way I can accomplish something like above?

How to convert all daily datat of a year to monthly data

Posted: 29 Apr 2016 05:55 AM PDT

First let me tell you what I want, I want to make a chart of a growth of a users mutual funds portfolio.

Now I have a user who invests in a portfolio last year.

Now I have a task which stores all the daily growth values of a users portfolio in user portfolio growth table.

Now as of current date I have all daily values of a portfolio growth in my user portfolio growth table.

What I want is to show monthly growth of a users portfolio on a graph.

So, my question here is how do I convert all the daily values to monthly values from date of his investment? So, that I can show it on a graph.

UserPortfolio Schema

# == Schema Information  #  # Table name: user_portfolios  #  #  id              :integer          not null, primary key  #  user_id         :integer          not null  #  portfolio_name  :string  #  amount          :integer          not null  #  investment_plan :string           not null  #  duration        :integer          default(1), not null  #  risk_level      :string           not null  #  created_at      :datetime         not null  #  updated_at      :datetime         not null  

UserPortfolioGrowth

# == Schema Information  #  # Table name: user_portfolio_growths  #  #  id                :integer          not null, primary key  #  user_portfolio_id :integer  #  appreciated_value :float  #  created_at        :datetime         not null  #  updated_at        :datetime         not null  #  

Thank You!

Generate array of daily avg values from db table (Rails)

Posted: 29 Apr 2016 04:58 AM PDT

Context: Trying to generating an array with 1 element for each created_at day in db table. Each element is the average of the points (integer) column from records with that created_at day. This will later be graphed to display the avg number of points on each day.

Result: I've been successful in doing this, but it feels like an unnecessary amount of code to generate the desired result.

Code:

def daily_avg      # get all data for current user      records = current_user.rounds        # make array of long dates      long_date_array = records.pluck(:created_at)        # create array to store short dates      short_date_array = []        # remove time of day      long_date_array.each do |date|          short_date_array << date.strftime('%Y%m%d')      end         # remove duplicate dates      short_date_array.uniq!        # array of avg by date      array_of_avg_values = []        # iterate through each day      short_date_array.each do |date|          temp_array = []            # make array of records with this day          records.each do |record|              if date === record.created_at.strftime('%Y%m%d')                  temp_array << record.audio_points              end          end          # calc avg by day and append to array_of_avg_values          array_of_avg_values << temp_array.inject(0.0) { |sum, el| sum + el } / temp_array.size      end      render json: array_of_avg_values  end  

Question: I think this is a common extraction problem needing to be solved by lots of applications, so I'm wondering if there's a known repeatable pattern for solving something like this?

Or a more optimal way to solve this?

(I'm barely a junior developer so any advice you can share would be appreciated!)

How to use order with uniq in a PostgreSQL

Posted: 29 Apr 2016 06:14 AM PDT

How can I use order with uniq?

auction.invoices.get_auction_invoices.item_invoices.  joins("INNER JOIN users ON users.id = invoices.usable_id").order("users.first_name").uniq  

The above query gives me following error:

This is my scopes

scope :item_invoices, ->{ joins(:invoice_details).where("invoice_details.invoiceable_type = ?", "Item")}

scope :get_auction_invoices, ->{where(:id => (item_invoices.skip_cancelled_invoice + donators.skip_cancelled_invoice))}

PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list LINE 1: ...oice_details.invoiceable_type = 'Item') ORDER BY users.firs... : SELECT DISTINCT "invoices".* FROM "invoices" INNER JOIN "invoice_details" ON "invoice_details"."invoice_id" = "invoices"."id" INNER JOIN users ON users.id = invoices.usable_id WHERE "invoices"."eventable_id" = $1 AND "invoices"."eventable_type" = $2 AND "invoices"."id" IN (1132, 1131, 777, 777, 777, 3013, 3024, 3024, 3024, 3024, 3041, 3041, 3013) AND (invoice_details.invoiceable_type = 'Item') ORDER BY users.first_name

rails 4 partial extension required under pdf template

Posted: 29 Apr 2016 04:25 AM PDT

I have using same partial under two different pages. The first one is under simple *.html.haml and the latter under *.pdf.haml.

Example: I have a partial as views/patient/reports/_invoice.html.haml

first Usage:- account.html.haml

= render partial: 'patient/reports/invoice'

second usage:- under invoice.pdf.haml

= render partial: 'patient/reports/invoice.html.haml'

why do I need to provide file extension in the latter one?

Error R13 (Attach error) -> Failed to attach to process on running console on heroku

Posted: 29 Apr 2016 04:05 AM PDT

I want to run rails console on heroku by typing command "heroku run rails console -a getpayad-staging" , but it kept on running and in logs i came up with error "Error R13 (Attach error) -> Failed to attach to process". I have seen couple of answers but not find perfect answer.

ruby on rails rest api with ruby for login page

Posted: 29 Apr 2016 04:22 AM PDT

i want to implement a ruby api for login page with ruby on rails backend in android mobile application, As i am new to this kindly help me to complete my task, and please tell the way to implement an API Thanks in advance

Cannot use password grant_type on 4.0.0 RC3 using Rails 5 Beta

Posted: 29 Apr 2016 03:41 AM PDT

I am trying to use doorkeeper on my Rails 5 app, and want to grant using password grant flow.

Versions used to do this is

  • Rails 5 Beta 4
  • Doorkeeper 4.0.0 RC3

I followed the intstructions here, and when I send a grant_type=password to the /oauth/token, I get an error.

{  "error": "unsupported_grant_type",  "error_description": "The authorization grant type is not supported by the authorization server."  }  

I tried this with a Rails4 app with doorkeeper 3.1.0, and had no problems.

I have created a new app and did the initial setup for doorkeeper, and have used the chrome extension called Advanced REST Client and the curl command to try to send username and password.

Have uploaded sample app on github.

https://github.com/saifis/doortest

How to show entries from the current month?

Posted: 29 Apr 2016 03:44 AM PDT

For the sake of explanation, I'm writing an app where a User can log their expenses.

In the User's show view, I want to only show the User's expenses from the current month.

My expenses table looks like this:

create_table "expenses", force: :cascade do |t|    t.date     "date"    t.string   "name"    t.integer  "cost"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.integer  "user_id"  end  

The date field is in the date format, so looks like: Thu, 14 Apr 2016

In my controller, I've got something like:

def show    month = Date.today.strftime("%m")    @user = User.find(params[:id])    @expenses = Expense.where(:user_id => @user.id, :date => month)  end  

Obviously, this isn't going to work, but it will be something along these lines, I'm guessing?

Any help would be great, thanks!

Ruby issue while configuring sensu checks

Posted: 29 Apr 2016 04:22 AM PDT

I have sensu server and sensu-client Installed on one machine (centos) and installed the the plugins through gem.

Everything was good when I run the check_ping.rb from the command line, but When I configure the same check in /etc/sensu/conf.d/ and check in the UI I am getting this ruby issue;

gem install sensu-plugins-network-checks  

I have ruby installed of 1.9.3 version

and configured EMBEDDED_RUBY=true

when I check the UI the below is the error I am facing

/opt/sensu/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- net/ping (LoadError)  from /opt/sensu/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/sensu-plugins-network-checks-0.2.4/bin/check-ping.rb:31:in `<main>'  Sensu::Plugin::CLI: ["Not implemented! You should override Sensu::Plugin::CLI#run."]  

Can someone help with this?

capistrano excute Makefile fail

Posted: 29 Apr 2016 03:38 AM PDT

I have a problem with excute Makefile

deploy.rb:

namespace :deploy do    after :deploy, :build_app do      on roles(:app), in: :groups do        execute "make production"      end    end  end  

Makefile:

production:      echo "make file production"  staging:      echo "make file staging"  all:      echo "make file all"  

error when run "cap production deploy"

DEBUG [1f0a117d] Command: make production  DEBUG [1f0a117d]    make: *** No rule to make target `production'.  Stop.  (Backtrace restricted to imported tasks)  cap aborted!  SSHKit::Runner::ExecuteError: Exception while executing as make production exit status: 2  make production stdout: make: *** No rule to make target `production'.  Stop.  make production stderr: Nothing written  

Debug run direct on server "make production" => echo "make file production"

And if excute with only "make" it will running to the first tag

--- Makefile addition

production:      npm install      npm run deploy-production      sudo docker rmi dashboard:latest; sudo echo 0      sudo docker build -t dashboard:$(VERSION) .      sudo docker tag -f dashboard:$(VERSION) dashboard:latest    staging:      npm install      npm run deploy-staging      sudo docker rmi dashboard:latest; sudo echo 0      sudo docker build -t dashboard:$(VERSION) .      sudo docker tag -f dashboard:$(VERSION) dashboard:latest  

Unable to establish relationship between two objects in Rspec

Posted: 29 Apr 2016 02:57 AM PDT

I'm writing an RSpec called Leads controller spec. In that I'm writing a test for create action of lead controller. Now my lead controller calls Project model to create an object(Project) which also creates Contact object and assigns it to project. but when I try to test whether my Project model creating a Contact object or no, The tests are getting failed. I don't know why my contact object is not getting created:(

My leads_controller_spec.rb

describe "POST #create" do      it "should create a contact too" do        my_lead = Fabricate(:project, id:  Faker::Number.number(10))        expect{        post :create, project: my_lead.attributes        }.to change(Contact, :count).by(1)      end      it "should be equal to last created contact" do        my_lead = Fabricate(:project, id:  Faker::Number.number(10))        post :create, project: my_lead.attributes        expect(Project.last.contact).to eq(Contact.last)      end    end  

leads_controller.rb

 def create      if @lead = Project.add_new_lead(lead_params)        @lead.create_activity :create_new_lead, owner: current_user        puts "My lead in create action: #{@lead.inspect}"      else        respond_to do |format|          format.html { redirect_to :back, :alert => "Email is already Taken"}        end      end        respond_to do |format|          format.html { redirect_to leads_path }        end     end  

Project.rb

def add_new_lead(inputs, data = {})        if !Contact.where(email: inputs[:email]).present?          contact = Contact.create(phone: inputs[:phone], email: inputs[:email], fullname: inputs[:fullname])          project = Project.create(name: inputs[:fullname], flat_status: inputs[:flat_status], flat_type: inputs[:flat_type], flat_area: inputs[:area], location: inputs[:locality], address: inputs[:site_address], customer_type: inputs[:customer_type])          project.contact = contact          project.save            project          else          return nil        end      end  

contact_fabricator.rb

require 'faker'  Fabricator(:contact) do  email { "email_#{Kernel.rand(1..30000)}@prestotest.com" }  fullname "project#{Kernel.rand(1..30000)}"  address "address#{Kernel.rand(1..30000)}"    end  

project_fabricator.rb

require 'faker'  Fabricator(:project) do        contact  end  

contact.rb

  field :phone,             type: String               field :email,             type: String    field :fullname,          type: String    field :status,            type: String,       default: "DEFAULT"    field :address,               type: String    field :new_address,       type: String    field :other_data,        type: Hash,         default: {}       validates_presence_of :email    validates_uniqueness_of :email, :message => "Email already taken"  

Unable to download .docx file using Capybara in ruby [duplicate]

Posted: 29 Apr 2016 02:56 AM PDT

This question is an exact duplicate of:

I am trying to download the .docs file by using capybara in ruby but all file is getting download except .docx. so plz tell me how can i download the .docx file using ruby

profile = Selenium::WebDriver::Firefox::Profile.new profile['browser.download.dir'] = '/tmp/' profile['browser.download.folderList'] = 2 profile['browser.helperApps.neverAsk.saveToDisk']="images/jpeg,application/pdf, application/doc, application/docx, text/csv, application/octet-stream"

profile['pdfjs.disabled'] = true profile.native_events = true @driver = Selenium::WebDriver.for :firefox, profile: profile puts '===============> Download will start now ===================>' @driver.get link puts '===============> Download is over ===================>'

belongs_to with different foreign key as well as primary key in the other table

Posted: 29 Apr 2016 02:56 AM PDT

I have two models:

Ticket and User

A ticket belongs_to a User, and a User has_many Tickets.

The thing here is that I want to associate these two models with:

The ticket has a ref_token column and the User has a token column. So, basically when trying to find the User for a given token (token123), I would expect the following query:

SELECT * FROM tickets WHERE token = 'token123'  

How can I set the association to accomplish this (basically I want to specify the columns that set the association. In this case they are different than the primary keys).

I have this now:

User    has_many :tickets, foreign_key: 'ref_token', primary_key: 'token'    Ticket    belongs_to :user, foreign_key: 'ref_token', primary_key: 'token'  

And I am able to do user.tickets, but I can't do ticket.user. It keeps returning nil.

Create a auth user using devise

Posted: 29 Apr 2016 03:58 AM PDT

Im using devise in my rails application and everything is working fine, what Im trying to do now is to allow users to login to my app using their github account and create a profile.

User.rb

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable, :omniauthable      has_one :profile      after_create :build_profile      def build_profile      self.create_profile    end      def self.create_with_omniauth(auth)      user = first_or_create do |user|        user.provider = auth['provider']        user.uid = auth['uid']        user.email = auth['info']['email']        user.password = Devise.friendly_token[0,20]      end    end  end  

routes.rb

devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }  

callbacks_controller.rb

class CallbacksController < Devise::OmniauthCallbacksController    def github      @user = User.from_omniauth(request.env["omniauth.auth"])      sign_in_and_redirect @user    end  end  

I also ran the correct migration to add provider and uid column to the users table

rails g migration AddColumnsToUsers provider uid    def change   add_column :users, :provider, :string   add_column :users, :uid, :string  end  

config/initializers/devise.rb

config.omniauth :github, 'CLIENT_ID', 'APP_SECRET', :scope => 'user:email'  

When i create a user using devise it all works fine and users are created, but when i click sign in with github on my registration page it merges the devise account and github account together leaving me with one account, its not creating an account with user github credentials. Even if i try and login using 2 different github accounts, it still for some reason only uses the first github account.

problem is github user can login but they are not being created as users, using their github credentials, i need users to login and create a profile with me.

Elasticearch result only on the basis of Term Frequency,avoiding Inverse document frequency and Field-length norm

Posted: 29 Apr 2016 06:47 AM PDT

I am using Elasticsearch version 2.3.1 for the search along with Ruby On Rails . I am using query_string for the search . It calculates the score on the basis of three factors :- 1.Term Frequency 2.Inverse document frequency 3.Field-length norm

I just want Term Frequency to be used for calculating score . Any way by which i could disable Inverse document frequency and Field-length norm factor in calculating score .

After some R&D on the topic i came with constant_score query which indirectly gives weightage to Term Frequency .

The problem which I know facing is that : e.g If i search for "good street food" it treats document having only "good" ,or "good food", or completely "good street food" with same score . But I want document with "good street food" should have higher score than "good food" , "good food" score higher than "good" .

The One solution which I came across is :

word_search1.each do |word_search|                          @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["group_name"] ,                query:word_search                }}}}                @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["message"] ,                query: word_search                }}}}                @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["tag_name"] ,                query: word_search                }}}}                @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["name"] ,                query: word_search                }}}}     end    Here word_search1=["good","street","food"]  

This some how solve my problem as know i am treating every word as different query rather than full string . But If someone has any better and optimize solution than this in which i could enter entire string in one line rather than loop and it gives priority to that document which has best matching or contains some word multiple times would love to know about that solution.

.docx file is not downloading with capybara

Posted: 29 Apr 2016 04:34 AM PDT

I am trying to download the .docs file by using capybara in ruby but all file is getting download except .docx. so plz tell me how can i download the .docx file using ruby

profile = Selenium::WebDriver::Firefox::Profile.new  profile['browser.download.dir'] = '/tmp/'  profile['browser.download.folderList'] = 2  profile['browser.helperApps.neverAsk.saveToDisk'] = "images/jpeg, application/pdf, application/doc, application/docx, text/csv, application/octet-stream"       profile['pdfjs.disabled'] = true   profile.native_events = true  @driver = Selenium::WebDriver.for :firefox, profile: profile   puts '===============> Download will start now ===================>'  @driver.get link   puts '===============> Download is over ===================>'  

Comparing values of Ruby XMLRPC datetime returned from API to normal Ruby DateTime object

Posted: 29 Apr 2016 02:51 AM PDT

I have an XMLRPC datetime returned from a remote API, and I want to perform normal comparison operations to a standard Ruby datetime object, such as >, <, >=, etc. I've read that XMLRPC has some strange datetime restrictions (such as it doesn't support values before or after a certain date) and using DateTime.parse() for the returned object doesn't work, with or without string interpolation.

How do you accurately convert an XMLRPC::DateTime object to a standard Ruby 2.2.2 DateTime object so I can execute comparisons, regardless of the date returned?

Localized dropdown with all month names

Posted: 29 Apr 2016 05:34 AM PDT

I am trying to make in Rails 4 a dropdown with all the months. I do it like this:

<select >      <% (1..12).each do |month| %>          <option value="<%= month %>"><%= Date::MONTHNAMES[month] %></option>      <% end %>  </select>  

The problem now is that I would like to localize it, but I can't apply the locate method on simple Strings with the names of the months.

How could I solve this?

Update

I know I can translate them myself, but I was hoping, since Rails is so kind to give me the names in English, if there was any way that Rails could give it to me in other languages as well.

No comments:

Post a Comment