Thursday, October 13, 2016

What does this ruby on rails code do? | Fixed issues

What does this ruby on rails code do? | Fixed issues


What does this ruby on rails code do?

Posted: 13 Oct 2016 07:37 AM PDT

I am working on a project and there has been an error with a customer getting responses. When they invoked an API call they got a 500 error. From the logs I identified the code causing the error which is shown below:

def send    adapter = @config['type']    response = "Adapters::#{adapter}".constantize.new(@config, @msisdn, @message).send    response ? (%w(200 201 202).include? response.code.to_s) : false  end  

The error is being caused by the line:

response ? (%w(200 201 202).include? response.code.to_s) : false  

My understanding of this line is limited so could do with some help understanding it better. I believe it is checking if the response contains one of the codes 200, 201 or 202 but not sure. Any help is appreciated.

How do I get User Profile Data from Janrain in Rails

Posted: 13 Oct 2016 07:35 AM PDT

How can I store values of a registration form which are going to Janrain database through Janrain capture authentication in my local postgresql database. My application is in RoR.

How to call Twitter gem methods on the twitter api client in the view file

Posted: 13 Oct 2016 07:27 AM PDT

I have spent hours looking through stackoverflow and can not find a simple explanation on how to call the twitter gem's methods in the view file. I have a very simple rails set up, with the following files and have set the twitter api client to be a global variable in order to test this. It works in the rails console, but I can not get it working in rails.

config/initializer/twitter.rb

require 'twitter'    $client = Twitter::REST::Client.new do |config|    config.consumer_key = 'xxxx'    config.consumer_secret = 'xxxx'    config.access_token = 'xxxx'    config.access_token_secret = 'xxxx'  end  

welcome_controller.rb

class WelcomeController < ApplicationController      def index    end    end  

routes.rb

Rails.application.routes.draw do    get 'welcome/index'    root 'welcome#index'  end  

index.html.erb (for welcome.rb)

<h1>Hi there</h1>    <p><%= $client.user %></p>  

It should just return my user details, as I have hard typed all my auth keys direct into the config file (I will abstract these later once I get this working).

Many thanks

rails tutorial app looking for wrong / missing application helper

Posted: 13 Oct 2016 07:22 AM PDT

I am getting the following error in rails:

AbstractController::Helpers::MissingHelperError in WelcomeController#index

Missing helper file helpers/c:/users/phil/desktop/blog/app/helpers/application_helper.rb_helper.rb

Rails.root: c:/Users/Phil/desktop/blog

app/controllers/application_controller.rb:1:in ' app/controllers/welcome_controller.rb:1:in

Notice the name of the missing helper in the error message:

application_helper.rb_helper.rb"

I went to the location for this file, and found "application_helper.rb" I changed the name of this file to match the name of the missing helper by adding an additional "_helper.rb" to the end to see what would happen. The error I got was:

Missing helper file helpers/c:/users/phil/desktop/blog/app/helpers/ application_helper.rb_helper.rb_helper.rb"

A third "_helper.rb!"

Anyone know what is going on here!?

Why is my expression matching somethign that clearly doesn't meet the expression?

Posted: 13 Oct 2016 07:29 AM PDT

I'm using Rails 4.2.7. I want to match the pattern, numbers, an arbitrary number of spaces, and a potential "+" at the end. So I wrote

2.3.0 :013 > /\d+\s*\+?/.match("40+")   => #<MatchData "40+">  

However, this is also matching

2.3.0 :012 > /\d+\s*\+?/.match("40-50")   => #<MatchData "40">   

What gives? The string "40-50" doesn't match the expression provided, but clearly I'm not doing something right in my regex. Any help is appreciated, -

Rails - cUrl GET with session cookie information - Getting 401

Posted: 13 Oct 2016 07:05 AM PDT

I am trying to cUrl GET a Rails URL in a hosted application. To test, I want to use a logged in session in my browser. I grabbed the cookies from the browser tab and passed it to cUrl command, but it's giving 401 Not Authorized.

I am using

curl -H 'session: 2asdfjlksfja32asdfuyio24fasdf' http://my-url/some-path  

The session is the key that is sent by browser to the server.

sign in VS sign up | devise with omniauth-facebook

Posted: 13 Oct 2016 07:08 AM PDT

  • Rails 5.0.0.1
  • Ruby 2.3.1p112
  • gem 'devise'
  • gem 'omniauth'
  • gem 'omniauth-facebook'

I have a app working with omniauth-facebook and Devise which must have some required extra attributes on signup page. It works very well but I'm having some difficulty on breaking authentication into two situations/behaviours:

  1. The specific page for user sign up by requiring some extra params.
  2. The specific page for user sign in (if the user already signed up).

The problem is on first_or_create method.

I need to create a record only on sign up page with my required params, otherwise, on the sign in page, I just need check if the user already signed up and redirect to sign up page if necessary.

Am I clear?

Model:

class User < ActiveRecord::Base      def self.from_omniauth(auth)          where(provider: auth.provider, uid: auth.uid).first_or_create do |user|              user.email = auth.info.email              user.password = Devise.friendly_token[0,20]              user.name = auth.info.name              user.avatar = auth.info.picture              user.username = auth.info.name.parameterize.dasherize.first(10) + Digest::SHA2.hexdigest("#{Time.now.utc}").first(5)              user.skip_confirmation!          end      end  end  

Callback:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController      def facebook          @user = User.from_omniauth(request.env["omniauth.auth"])            params = request.env["omniauth.params"]          @user.username = params["username"]          @user.newsletter = params["newsletter"]          @user.diet_id = params["diet_id"]            if @user.persisted?              sign_in_and_redirect @user, event: :authentication              set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?          else              session["devise.facebook_data"] = request.env["omniauth.auth"]              redirect_to new_user_registration_url          end      end        def failure          redirect_to root_path      end  end  

Relevant code for signup page:

= form_tag user_facebook_omniauth_authorize_path(newsletter: @user.newsletter, username: @user.username, diet_id: @user.diet_id) do  

Relevant code for sign in page:

= link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path   

Can I set rspec --format documentation as the default?

Posted: 13 Oct 2016 07:27 AM PDT

Per the Rspec documentation, by default when you run rspec you get the progress formatter (looks like this: ".....").

There is another formatting option rspec --format documentation that goes through each test one by one. My question: how can I enable --format documentation by default without having to type it in the command line every time?

SQLi safe? Multiple .where request using OR

Posted: 13 Oct 2016 07:01 AM PDT

Using Rails 5. Is this safe, or could this query be SQL injected?

(There's a form for selecting the region_ids on my site)

# results = results.joins(:regionmemberships).where("regionmemberships.region_id = ? OR regionmemberships.region_id = ?", 0, 2) if region_id.present?  

I've read that results.where('regionmemberships.region_id = ?', region_id)

.. is safe. But is the first statement, when using OR also safe?

Or is there a more secure way to write this?

Rails 4/5 Sending Dynamic ActionMailer::Base.mail email With Attachment labeled Noname

Posted: 13 Oct 2016 06:29 AM PDT

I've taken a look at similar posts that mostly deal with sending an attachment by creating a view and controller, such as:

PDF attachment in email is called 'Noname'

but I've got a process that generates files in the background dynamically and need to attach it to a recipient list using ActionMailer::Base.mail. Below is the code:

def send_email(connection)      email = ActionMailer::Base.mail(to: connection['to'], from: connection['from'], subject: 'Sample File', body: "<p>Hello,</p><p>Your data is ready</p>", content_type: 'multipart/mixed')      email.cc = connection['cc'] if connection['cc'].present?      email.bcc = connection['bcc'] if connection['bcc'].present?      @files.each do |file|        report_file_name = "#{@start_time.strftime('%Y%M%dT%I%m%s')}_#{file[0]}.xlsx"        file_location = "#{Rails.root}/tmp/#{report_file_name}"        email.attachments[report_file_name] = File.open(file_location, 'rb'){|f| f.read}      end      email.deliver if email    end  

I can see in the logs that it's sending with the content but assume it's sending as Noname because it can't find the view. Any way to get this to work successfully?

Below is the sample output:

Sent mail to sample@sample.com (383.9ms) Date: Thu, 13 Oct 2016 08:47:30 -0400 From: Sample To: Recipient Message-ID: <57ff326270f15_421f1173954919e2@ulinux.mail> Subject: Sample File Mime-Version: 1.0 Content-Type: multipart/mixed; charset=UTF-8 Content-Transfer-Encoding: 7bit

-- Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; filename=20161012T08101476259208_Data.xlsx Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=20161012T08101476259208_Data.xlsx Content-ID: <57ff326270f15_421f1173954919e2@ulinux.mail>

UEsDBBQAAAAIAO.. ... ...ADUFQAAAAA=

GemNotFound rake when using whenever in development

Posted: 13 Oct 2016 07:21 AM PDT

I'm getting this one error I don't understand (I'm fairly new to rails) when using the gem 'whenever' in development mode.

What I did was update config/schedule.rb and run

whenever --update-crontab --set environment='development'  

crontab -l lists:

* * * * * /bin/bash -l -c 'cd /home/vic/Desktop/WorkflowProject && bundle exec bin/rails runner -e development '\''Task.new2'\'' >> log/whenever.log 2>&1'  

at config/schedule.rb

set :output, 'log/whenever.log'    every 1.minute do    runner "Task.new2"  end  

at log/whenever.log

bundler: failed to load command: bin/rails (bin/rails)  Bundler::GemNotFound: Your bundle is locked to rake (11.3.0), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of rake (11.3.0) has removed it. You'll need to update your bundle to a different version of rake (11.3.0) that hasn't been removed in order to install.  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/definition.rb:179:in `rescue in specs'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/definition.rb:173:in `specs'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/definition.rb:233:in `specs_for'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/definition.rb:222:in `requested_specs'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/runtime.rb:118:in `block in definition_method'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/runtime.rb:19:in `setup'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler.rb:99:in `setup'  /home/vic/.rvm/gems/ruby-2.3.1/gems/bundler-1.13.2/lib/bundler/setup.rb:20:in `<top (required)>'  /home/vic/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  /home/vic/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  

I would grealy appreciate the help, thank you very much!

How to format attributes while exporting it to CSV in Rails 4

Posted: 13 Oct 2016 06:21 AM PDT

I'm trying to export some records to CSV, so in my controller I have the following:

...  send_data @orders.to_csv, filename: "orders-#{Date.today}.csv"  ...  

And in model I have the following:

     def self.to_csv            attributes = %w{ customer_name created_at order_id currency discount subtotal_tax total }            CSV.generate(headers: true) do |csv|            csv << attributes            all.each do |order|              if order['created_at']                order['created_at'] = order['created_at'].strftime("%d/%m/%Y")              end              csv << attributes.map{ |attr| order.send(attr) }            end          end          end  

I'd like to format some of the parameter as you can see from this code:

if order['created_at']    order['created_at'] = order['created_at'].strftime("%d/%m/%Y")  end  

So I'd have the time formatted how I want, however this is not working.

Any ideas why?

Rails 4 + Postgres: Randomly cannot connect to development server

Posted: 13 Oct 2016 06:57 AM PDT

I am running Rails 4.2.2 and my postgres gem is 0.17.1 and everything was running fine yesterday but today when I opened the console and tried connecting to the database I saw this error:

PG::ConnectionBad: could not connect to server: No such file or directory      Is the server running locally and accepting      connections on Unix domain socket "/tmp/.s.PGSQL.5432"?  

...then when I tried connecting to the database through running psql, I see the following:

dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib    Referenced from: /usr/local/bin/psql    Reason: image not found  Abort trap: 6  

As far I know I havent changed anythingsince yesterday so I'm not sure why this is happenning. I tried adding host: localhost to my database.yml with no luck. It may be worth noting when I try to connect to the DB using a program like PSequel, I see the following:

could not connect to server: Connection refused      is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?  

Has anyone seen this?

Get count of one-to-many records efficiently

Posted: 13 Oct 2016 06:44 AM PDT

I have two tables: App (with a release_id field) and User.

Models

class App < ActiveRecord::Base    has_one :user  end    class User < ActiveRecord::Base    belongs_to :app  end  

Class

class Stats::AppOverview    def initialize(from:, apps:)      @from = from || Date.new(2010)      @apps = apps    end      def total_count      { apps: { total: total_app, with_user: app_with_user } }    end      private      def app_since      @apps.where('created_at >= ?', @from)    end      def total_app      devices_since.count    end      def app_with_user      User.where(app: app_since).count    end  end  

I would like to return

  1. the number of app records for a given array of release_id
  2. the number of app records that belong to each user, satisfying other criteria

This is how I use the class

Stats::AppOverview.new(from: 1.month.ago.iso8601,     apps: App.where(release_id: [1,2,3,4,5,19,235]).total_count  #=> { apps: { total: 65, with_user: 42 } }  

For the moment I do it in two queries, but is it possible to put them in the same query? Is this possible using active record?

Whitelisting content-type to only application/json for approproate requests in Rails

Posted: 13 Oct 2016 05:58 AM PDT

I have an API that handles almost exclusively application/json in Rails. A few endpoints can handle application/x-www-form-urlencoded for file-uploads.

I want to enforce the content-types: when a client adds anything other than application/json I want to send an 406 - not acccepted error back, in my ApplicationController

before_action :require_content_type_json    def require_content_type_json    return if request.content_type == Mime::JSON.to_s    head status: 406  end  

However, RFC 2616 (http) states that:

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

I roughtly interpret that as "when the request comes with a body, the content-type must be provided by the client, else the server should assume "application/octet-stream".

Since I cannot handle octet-stream, I want to return 406 - not accepted too, there.

So, how do I detect whether a user should have sent a content-type header along? Is it enough to simply check for !request.body.empty?: body is not empty?

Or should I assume that only GET/OPTIONS/HEAD requests have no body and all others do and should require a content-type?

Does Rails have any helpers or classes in place to deal with this?

RegExp to match 10 lines or less, that's cross-compatible in Ruby and Javascript

Posted: 13 Oct 2016 05:51 AM PDT

I have a Rails backend that powers a Node frontend, and part of the Rails backend is validation on fields, that we than expose and pass to the Node frontend to consume.

Most of our validation rules are pretty simple things, blacklisting certain characters, etc.

But one rule is that a certain field can contain no more than 10 new lines.

Now, in Ruby this would be simple to achieve with the following:

/\A(^.*$\r?\n?){0,10}\z/  

However, this is incompatible with Javascript, as the end of string and end of line characters are the same.

One way I tried which was compatible with both was the following:

/\A([^\n]*\n[^\n]*){10,}\z/  

But whilst this worked fine on the Node side, this appears to be a case of Catastrophic backtracking as if the test string gets too complicated, it takes exponentially longer to complete the Regular Expression.

I know this would be a lot simpler without using a Regular Expression, but due to the current setup of our stack, it is not an option to use anything than is not supported by the Active Record Validations.

Any help would be greatly appreciated in this, as I'm banging my head into a brick wall trying to figure it out!

Validation issue using multiple Proc objects

Posted: 13 Oct 2016 07:14 AM PDT

I have validation with Proc and problem with it

validates :subcategory, presence: true,   if: Proc.new {|product| product.detail.blank?} && Proc.new { |product|  product.category.id != 16 }  

My problem is when i have true in second proc my validation fires.

Why is it so? Should it not return false because false && true=>false?

Rails - Objects not refreshed after Saving or Deleting

Posted: 13 Oct 2016 06:01 AM PDT

I am doing some saving and destroying operation on a object which behaves weird.

  if already_in_server          bookmark_obj = array_already_bookmarked.detect {|bookmark| bookmark.article_doi == article_doi["doi"]}          if 1 == article_doi["isbookmarked"]            binding.pry            bookmark_obj.updated_at = Time.now            bookmark_obj.save          else            bookmark_obj.destroy          end   end  

Association between them:

up has_many -----> bookmarks  bookmark belongs_to --> up  

But when I try to call up.bookmarks, It also returns destroyed objects and

bookmark_obj.updated_at = Time.now   

is not updated.

setting tooltip using Chartkick on scatter graph

Posted: 13 Oct 2016 05:36 AM PDT

This is my Chartkick scenario, for each student there is an amount of time spent, and a number of exercises completed. The scatter graph plots the time spent vs number of exercises completed for each student. The teacher needs to be able to see the name of the student in the tooltip when they hover over a point.

Having looked at the underlying google chart it looks like this is supported: https://developers.google.com/chart/interactive/docs/customizing_tooltip_content

Is there a way of passing the tooltip string into ChartKick so that I can specify the name of each student?

I'm currently calling like this: scatter_chart @time_spent_vs_mastered, {library: {label: 'student', title: 'Items mastered vs time spent', hAxis: {title: "items mastered"}, vAxis: {title: "time spent (hrs)"}}}

I'm using Google Charts from Chartkick.

Devise not sending emails after upgrading to Rails 5

Posted: 13 Oct 2016 05:30 AM PDT

I am having issues to get Devise working after upgrading from Rails 4.2 to 5. Running on Rails 4 everything worked like a charm, but post update no notifications were sent in development and production. Initially, I left all the settings as they were - once aware of the problem I made a few changes, and this is what I have at the moment (Please note I re-run the devise installer at some point, which replaced the initializer/devise.rb)

development.rb

Rails.application.configure do    ..    config.action_mailer.raise_delivery_errors = true    config.action_mailer.delivery_method = :smtp    config.action_mailer.perform_deliveries = true    config.action_mailer.default :charset => "utf-8"    config.action_mailer.perform_caching = false    config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }  end  

initializers/devise.rb

  # ==> Mailer Configuration    # Configure the e-mail address which will be shown in Devise::Mailer,    # note that it will be overwritten if you use your own mailer class    # with default "from" parameter.    config.mailer_sender = 'noreply@mydomain.com'      # Configure the class responsible to send e-mails.    config.mailer = 'Devise::Mailer'      # Configure the parent class responsible to send e-mails.    config.parent_mailer = 'ActionMailer::Base'  

I also followed the instructions issued by devise (i.e. extending routes, etc.)

The only specialty that had been added is that I am using Active Job to deliver ActionMailer messages and therefore added this to my User Model to override send_devise_notification:

def send_devise_notification(notification, *args)    devise_mailer.send(notification, self, *args).deliver_later  end  

Looking at the console output, it does not suggest in any way that the devise/mailer/confirmation_instructions.html.haml is ever being rendered.

DEBUG: Chewy strategies stack: [2] -> atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  Started POST "/en/users" for ::1 at 2016-10-13 14:05:41 +0200  DEBUG: Chewy strategies stack: [2] <- atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  Processing by RegistrationsController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"CZ0wqg4a/atdIYfZ/QOj3b/UsTl0oqkBrcZjS9ZF6vaJi4JSD3nO2EGcCVVaM+5QYTM7+Iw40q+zkxAWSDVj9A==", "user"=>{"country"=>"AF", "email"=>"right@right.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "tcagree"=>"1"}, "g-recaptcha-response"=>"", "commit"=>"Sign up for free!", "locale"=>"en"}     (0.3ms)  BEGIN    User Exists (0.9ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "right@right.com"], ["LIMIT", 1]]    SQL (13.4ms)  INSERT INTO "users" ("email", "encrypted_password", "confirmation_token", "confirmation_sent_at", "created_at", "updated_at", "roles_mask", "country") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"  [["email", "right@right.com"], ["encrypted_password", "$2a$11$BzxtTw3PwaH06K6tpNlXHOtv.7sxgmVGhZyouIMzDfXP.cxnF2YGy"], ["confirmation_token", "Q-k8t3k-AmAoQoxggdcW"], ["confirmation_sent_at", 2016-10-13 12:05:42 UTC], ["created_at", 2016-10-13 12:05:42 UTC], ["updated_at", 2016-10-13 12:05:42 UTC], ["roles_mask", 64], ["country", "AF"]]    SQL (0.7ms)  UPDATE "users" SET "id" = $1, "encrypted_password" = $2, "confirmation_token" = $3, "confirmation_sent_at" = $4, "created_at" = $5, "updated_at" = $6, "username" = $7, "roles_mask" = $8, "unconfirmed_email" = $9, "country" = $10 WHERE "users"."id" = $11  [["id", 16], ["encrypted_password", "$2a$11$BzxtTw3PwaH06K6tpNlXHOtv.7sxgmVGhZyouIMzDfXP.cxnF2YGy"], ["confirmation_token", "G3VSGdh-Q2C3sg1mxevB"], ["confirmation_sent_at", 2016-10-13 12:05:42 UTC], ["created_at", 2016-10-13 12:05:42 UTC], ["updated_at", 2016-10-13 12:05:42 UTC], ["username", "user-3aff9416"], ["roles_mask", 64], ["unconfirmed_email", "right@right.com"], ["country", "AF"], ["id", 16]]     (3.5ms)  COMMIT  Redirected to http://localhost:3000/  Completed 302 Found in 377ms (ActiveRecord: 18.8ms)      DEBUG: Chewy strategies stack: [2] -> atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  Started GET "/" for ::1 at 2016-10-13 14:05:42 +0200  DEBUG: Chewy strategies stack: [2] <- atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  Processing by StaticPagesController#redirect as HTML  Redirected to http://localhost:3000/en  Filter chain halted as :set_locale rendered or redirected  Completed 302 Found in 14ms (ActiveRecord: 0.0ms)      DEBUG: Chewy strategies stack: [2] -> atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  Started GET "/en" for ::1 at 2016-10-13 14:05:42 +0200  DEBUG: Chewy strategies stack: [2] <- atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  Processing by StaticPagesController#welcome as HTML    Parameters: {"locale"=>"en"}    Rendering static_pages/welcome.html.haml within layouts/home    Rendered shared/_fb_image.html.haml (2.3ms)    Rendered static_pages/welcome.html.haml within layouts/home (13.4ms)    Rendered layouts/navs/_standard.html.haml (6.8ms)    Rendered layouts/_flashes.html.haml (3.0ms)    Rendered layouts/general/_shim.html.erb (0.9ms)    Rendered layouts/scripts/_google_analytics.html.haml (1.8ms)    Rendered layouts/_navbar.html.haml (2.6ms)    Rendered cookies_eu/_consent_banner.html.haml (1.8ms)    Rendered layouts/_footer.html.haml (2.8ms)    Rendered layouts/_base.html.haml (557.4ms)  Completed 200 OK in 606ms (Views: 601.2ms | ActiveRecord: 0.0ms)      DEBUG: Chewy strategies stack: [2] -> atomic @ /Users/georg/.rbenv/versions/2.2.4/lib/ruby/gems/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17  

Any input would be highly appreciated

Forgot to mention current versions I am running on: Devise - 4.2.0, Ruby - ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin15], Rails - Rails 5.0.0

undefined method `email' for nil:NilClass (is email necessary in the code below)

Posted: 13 Oct 2016 05:43 AM PDT

enter image description here this is at the error screen at localhost:3000 as I run the rails server.

Rails 5 - regex - for string not found [duplicate]

Posted: 13 Oct 2016 04:42 AM PDT

This question already has an answer here:

In my app that I am building to learn Ruby and Rails, I am working on finding data and am relatively new to regex (studying the mastering regex book). In this case better said: combination of presence and absence of data.

Case: if a document contains a combination of strings, I want to classify its document type.

Assume this content: delivery note 12345 invoice number 45tr3 versus delivery note 12345 invoice number 45tr3 credit note 645211.

How can I figure out in a regex if the term credit note is absent, while the term invoice number is present?

If it is absent, it is document type A, if it is present document type B.

Ruby is getting wrong class name from my code

Posted: 13 Oct 2016 04:34 AM PDT

Weird error, I'm calling ::Facility::ProcedureDecorator, but for some reason on my staging server ruby wants to call ProceduresDecorator instead. Any ideas what is going on?

Here are some samples:

NameError: uninitialized constant #<Class:0x00555f1ea188d0>::ProceduresDecorator  Did you mean? Facility::ProcedureDecorator  File "/app/app/admin/facility.rb" line 32 in edit      def edit    @facility = Facility.includes([:documents, :procedures]).find(params[:id])    @facility_documents = @facility.documents    @possible_document_kinds = FacilityDocument.kinds.map { |k, _| [k.humanize, k] }    @facility_procedures = ::Facility::ProcedureDecorator                           .decorate_collection(@facility.procedures) # line 32    @facility_info = ::Facility::InfoDecorator.decorate(@facility.info)    @possible_procedures = @facility_procedures.map { |procedure| [procedure.name, procedure.id] }    @templates = @facility.emergency_event_templates    @white_label = @facility.white_label  end  

Conditional Validation for Serialized Array

Posted: 13 Oct 2016 07:16 AM PDT

How can I create a validation where committed presence needs to be true only if the challenge's category is habit?

class Challenge < ActiveRecord::Base    CATEGORY = ['goal', 'habit']    serialize :committed, Array    validates :committed, presence: true, if: :habit # I also tried with 'habit' & 'Habit'  end  

Heroku error: We're sorry, but something went wrong

Posted: 13 Oct 2016 06:04 AM PDT

i have deployed an app to heroku(finance tracker under "ROR developer course" from udemy.com). The login button works fine but when i click on the signup button, it gives me this error

We're sorry, but something went wrong.  If you are the application owner check the logs for more information.  

I have ran heroku run rake db:migrate successfully. I used devise gem for authentication. Pls any idea someone??....thanks

How to put text field instead of %{...} in Rails?

Posted: 13 Oct 2016 04:55 AM PDT

I have the next string:

'The weather is too %{condition} today.'  

Now I want to paste instead of %{condition} a text field, so it will look like:

The weather is too __text_field__ today.  

I've tried:

if text.include? "%{"      =text_field_tag(:q, nil, class: "")  

but it pastes after the whole sentence. How can I put/replace %{} with my text field?

How do I get params in rails that are only from the URL?

Posted: 13 Oct 2016 04:14 AM PDT

I'm writing a rails mountable gem which fires custom javascript events based on what controller and action being rendered.

I would like to add a feature where the params from the URL are available to event handlers:

// 'PATCH /users/:user_id/tasks/:id'  $(document).on('tasks#update', function(data, params){    console.log(params['user_id'], params['id']);  });  

For security reasons I would like to limit this to the params which originate from the URL and not from the request body.

Since this is library and not application code I can't just use URI.parse as the key mappings are not known.

How do I get a subset of the params that are only the router matches?

Rails Client_side_validation error message is not generating on turbolinks:load

Posted: 13 Oct 2016 03:50 AM PDT

Rails Client_side_validation error message is not generating on turbolinks:load but generates on page load (page refresh).

Rails Version: Version 4.2.6 Client_Side_Validation: Version 4.2.7

Model:

class Comment < ActiveRecord::Base    validates :content, presence: true      belongs_to :post    belongs_to :user  end  

Form:

<%= form_for [@post, @post.comments.build], validate: true do |f| %>      <div class="input-group">      <%= f.text_field :content, class: "form-control", autocomplete: :off %>      <span class="input-group-btn">        <%= f.submit "Send", class: "btn btn-primary pull-right" %>      </span>    </div>    <% end %>  

Generated HTML:

<form data-validate="true" novalidate="novalidate" class="new_comment" id="new_comment" action="/posts/21/comments" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="ZmpADuX73JqNvAh5wljYCmk68wXioVLFP1YDHY+71l4YADgQglKiQAODBrc5OrXvioqurjI5/JwqfO2qJXPPvg==" />      <div class="input-group">      <input class="form-control" autocomplete="off" type="text" name="comment[content]" id="comment_content" />      <span class="input-group-btn">        <input type="submit" name="commit" value="Send" class="btn btn-primary pull-right" />      </span>    </div>  </form>    <script>  //<![CDATA[  if(window.ClientSideValidations===undefined)window.ClientSideValidations={};window.ClientSideValidations.disabled_validators=["uniqueness"];window.ClientSideValidations.number_format={"separator":".","delimiter":","};if(window.ClientSideValidations.patterns===undefined)window.ClientSideValidations.patterns = {};window.ClientSideValidations.patterns.numericality=/^(-|\+)?(?:\d+|\d{1,3}(?:\,\d{3})+)(?:\.\d*)?$/;if(window.ClientSideValidations.forms===undefined)window.ClientSideValidations.forms={};window.ClientSideValidations.forms['new_comment'] = {"type":"ActionView::Helpers::FormBuilder","input_tag":"\u003cdiv class=\"field_with_errors\"\u003e\u003cspan id=\"input_tag\" /\u003e\u003clabel for=\"\" class=\"message\"\u003e\u003c/label\u003e\u003c/div\u003e","label_tag":"\u003cdiv class=\"field_with_errors\"\u003e\u003clabel id=\"label_tag\" /\u003e\u003c/div\u003e","validators":{"comment[content]":{"presence":[{"message":"can't be blank"}]}}};  //]]>  </script>  

Issue:

The generated input HTML should look like this:

<input class="form-control" autocomplete="off" type="text" name="comment[content]" id="comment_content" data-validate="true" />  

data-validate="true" is not generating on turblinks:load but generates ok when the page is refreshed.

Does anyone know of a solution for this?

Nginx + Ruby redirect www to not-www and http to https

Posted: 13 Oct 2016 03:49 AM PDT

Guys! Help is needed. Have a website https:// origitea.ru certificate is issued only for origitea.ru domain and does not work on www.origitea.ru. The site on Ruby, Nginx server.

How can I make a redirect worked with http:// www.origitea.ru at https: //origitea.ru and the same for the https:// www.origitea.ru to https:// origitea.ru ? It is necessary that in any indication, only open the site https://origitea.ru Yes there were already some answers then, but he did not answer private. The fact that there is an appeal to the platform on the lips, and ports 80 and 443 seem to obey initially platform.

Redirect is not currently running properly. Help me please. THX

                         upstream puma {    server unix:///var/www/www-root/data/www/origitea.ru/apps/origiteya/shared/tmp/sockets/origiteya-puma.sock;  }    server {      server_name origitea.ru www.origitea.ru;          return 301 https://origitea.ru$request_uri;           charset off;      disable_symlinks if_not_owner from=$root_path;      index index.html index.php;      root $root_path;      set $root_path /var/www/www-root/data/www/origitea.ru;      access_log /var/www/httpd-logs/origitea.ru.access.log ;      error_log /var/www/httpd-logs/origitea.ru.error.log notice;      include /etc/nginx/vhosts-includes/*.conf;      include /etc/nginx/vhosts-resources/origitea.ru/*.conf;      location / {          location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {              try_files $uri $uri/ @fallback;          }          location / {              try_files /does_not_exists @fallback;          }          location ~ [^/]\.ph(p\d*|tml)$ {              try_files /does_not_exists @fallback;          }      }      location @fallback {          proxy_pass http://puma;          proxy_redirect http://puma /;          proxy_redirect http://127.0.0.1:8080 /;          proxy_set_header Host $host;          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;          proxy_set_header X-Forwarded-Proto $scheme;          access_log off ;      }      listen 10.10.0.100:80;      ssi on;  }  server {      server_name origitea.ru www.origitea.ru;      charset off;      disable_symlinks if_not_owner from=$root_path;      index index.html index.php;      root $root_path;      set $root_path /var/www/www-root/data/www/origitea.ru;      access_log /var/www/httpd-logs/origitea.ru.access.log ;      error_log /var/www/httpd-logs/origitea.ru.error.log notice;      include /etc/nginx/vhosts-includes/*.conf;      include /etc/nginx/vhosts-resources/origitea.ru/*.conf;      location / {          location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {              try_files $uri $uri/ @fallback;          }          location / {              try_files /does_not_exists @fallback;          }          location ~ [^/]\.ph(p\d*|tml)$ {              try_files /does_not_exists @fallback;          }      }      location @fallback {          proxy_pass http://puma;          proxy_redirect http://puma /;          proxy_redirect http://127.0.0.1:8080 /;          proxy_set_header Host $host;          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;          proxy_set_header X-Forwarded-Proto $scheme;          access_log off ;      }      ssi on;      add_header Strict-Transport-Security "max-age=31536000;";      listen 10.10.0.100:443;      ssl on;      ssl_certificate "/var/www/httpd-cert/www-root/origitea.ru.crt";      ssl_certificate_key "/var/www/httpd-cert/www-root/origitea.ru.key";      ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;      ssl_prefer_server_ciphers on;      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;  }  server {      # server_name example.com;      root /var/www/www-root/data/www/origitea.ru/origiteya/current/public;    access_log /var/www/www-root/data/www/origitea.ru/apps/origiteya/current/log/nginx.access.log;    error_log /var/www/www-root/data/www/origitea.ru/apps/origiteya/current/log/nginx.error.log info;      location ^~ /assets/ {      gzip_static on;      expires max;      add_header Cache-Control public;    }      try_files $uri/index.html $uri @puma;    location @puma {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;        proxy_pass http://puma;          proxy_redirect http://puma;          proxy_set_header Host $host;          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;          proxy_set_header X-Forwarded-Proto $scheme;          access_log off ;    }      error_page 500 502 503 504 /500.html;    client_max_body_size 100M;    keepalive_timeout 10;  }  

rails nested attributes rails record_not_found when update

Posted: 13 Oct 2016 03:43 AM PDT

I have 2 models like:

class Customer < ActiveRecord::Base   has_many :passengers   accepts_nested_attributes_for :passengers, allow_destroy: true  end    class Passenger < ActiveRecord::Base   belongs_to :customer  end  

customer_params contain :

:name,...  :passengers_attributes: [:id, :name, :_destroy]  

and when pass passengers_attributes to update customer (id=1) like

{    "passengers_attributes": [      {        "name": "abc",        "id": 5      }    ]  }  

With passenger "abc" is new record

When i run customer.update_attributes!(customer_params), it raise error ActiveRecord::RecordNotFound: Couldn't find Passenger with ID=5 for Customer with ID=1

Do you know this error? i need your help. Thanks

No comments:

Post a Comment