dimanche 31 décembre 2017

How to create multiple login pages with Devise

I'm using Devise to authenticate. However, I have 3 profile types, and I created the rails g devise MODEL command for my users (Admim, dev and manager), but Devise created a login page for each profile type, I would like to unify and log in using only one page!.

My idea is to create a view by picking up the email and the password and passing it to a custom controller inheriting from ** Devise :: Sessions ** and overwriting the method that logs in, searching the email in the 3 tables and redirecting the user to the Controller responsible for his profile.

How could I do this "manual login" with Devise? Any other solution to this?

samedi 30 décembre 2017

access all events from clockwork manager to controller

Am using gem clockwork for running scheduled jobs. I need to access all events defined in clock.rb for manually trigger the clockwork events when it fails.

For that I forked the clockwork gem by adding attr_reader: events in clockwork/manager.rb file.

clock.rb

module Clockwork
  every(10.seconds, 'job1') do
    p Clockwork.manager.events
  end
end

By using Clockwork.manager.events in clock.rb it returns all events that defined in clock.rb.

mycontroller.rb

module Admin
  class MyController < AdminController

    require 'clockwork'

    def index
      @events = Clockwork.manager.events
    end
  end
end

But while using it in controller it returns empty value.

How to get all clockwork events in controller?

vendredi 29 décembre 2017

Rails 5 - How to get serializable_hash for activerecord?

In rails 5, I am trying to get a data in serializable_hash format. First set of data format is in correct but second set of data is in different format. The Comment module works like parent and children format, one comment has_many comments by adding parent_comment_id.

For parent comment, now data is {id: 77, name: "l1", verified: true, category: "Movie", slug: "l1", …}

For child comment, data is coming like {id: 78, name: "l2", category_id: 61, …}

Here I need to get second set of data for comments as same as first format. I have tried using serializable_hash but it supports only single row. How can I achieve this for all comments(has_many association)?

Error when delete comment Ruby on Rails

When I delete comment I see

undefined method 'each' for nil:NilClass

Also, the user cannot delete his account if has posted... It makes the error.

This is code

<p id="notice"><%= notice %></p>

<h1>Comments</h1>

<table>
  <thead>
    <tr>
      <th>Link</th>
      <th>Body</th>
      <th>User</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @comments.each do |comment| %>
      <tr>
        <td><%= comment.link_id %></td>
        <td><%= comment.body %></td>
        <td><%= comment.user %></td>
        <td><%= link_to 'Show', comment %></td>
        <td><%= link_to 'Edit', edit_comment_path(comment) %></td>
        <td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Comment', new_comment_path %>

Ruby odd number of arguments for hash error

case look
  when 'side'
        hash1 = {
            'num' => 5,
            'style' => 'sideStyle',
        }

  when 'front'
        hash1 = {
            'num' => 8,
            'style' => 'frontStyle',
        }

  when 'back'
        hash1 = {
            'num' => 4,
            'style' => 'backStyle',
            'special' => 'yes',
        }

  else
        hash1 = {
            'num' => 2,
            'style' => 'noStyle',
        }
  end

  myStyle = Hash[hash1]

My piece of code looks like this.

when I run this code I get "odd number of arguments for Hash".

is this the correct way to from an hash? could someone please help me how to get it resolved.

Sorting Records on a Custom calculated value at the runtime- rails

I have Two models Product, Price

Product 
 has_many :prices

Price
 belongs_to :product

we have price_type and price_date attributes in the Price Model. price_type can be default, weekend, specific_date for a particular Product.

Product can have single price on a day like either it is weekend, or a specific_date otherwise default.

price_date will be matter when price_type will be specific_date

Now The problem is,

Date.today is passing in the parameters

I want to get all the products in the sorted by price on that date which is passing.

I'm trying to find the solution since a long time!

Please Help Me!

Thanks

Translate error messages using rails (I18n) Api

I am using rails internationalization api for activerecord translations .I am having trouble translating error messages. How to translate multiple error messages from different files in my project?I am have files named application_draft.rb,team.rb,user.rb,todo.rb inside my models folder.I want to translate error messages in them ,here's my en.yml file:

errors:
        models:
         -team:
         -application_draft:
         -conference:
         -todo:
         -user:
            attributes:
              roles:
                too_many_reviewers: too many reviewers
                multiple_sel_error: must not be selected twice
                must_accepted: must have been accepted
                one_app_allowed: Only one application may be lodged
                confirmed_email_address: Please make sure every student confirmed the email address.
                wrong_date_sel: must be a later date than start date
                no_more_than_two: "there cannot be more than 2 students on a team."
                cannot_changed: can't be changed

I have implemented this code and throws error(means it did not work). Here's my one of application_draft.rb and todo.rb error code snippets:

application.rb:

def different_projects_required
  if project1 && project1 == project2
    errors.add(:projects, :multiple_sel_error)
  end
end

todo.rb

def validate_number_of_reviewers
  errors.add(:user, :too_many_reviewers) if application.todos.count > 3
end
end

How to translate these both avoiding duplication errors?

jeudi 28 décembre 2017

Trying to find all classes that include a module

Before I dive into question I m gonna try to explain the structure of my codebase.

1) There might be a class X which definition would be :

module ParentModule
   class X
   end
 end

2) Also there might be a nested class under different module :

module ParentModule
   module ChildModule
     class Y
     end
   end
 end

3) Also there might be just a module with some classes inside:

module ParentModule
   module OtherModule
     def some_awesome_method
       ..does something
     end
   end  
 end

I m trying to get a list of classes within my ParentModule that include OtherModule. Here is what I have so far, working well :

include_resources = ->(klass) {
        begin
          klass_string = klass.to_s
          klass_resource = klass_string.constantize
          klass_string if klass_resource.included_modules.include?(OtherModule)
        rescue NameError # skip all bad naming and other irrelevant constant loading mishaps
          next
        end
      }

So if I do ParentModule.constants.find_all(&include_resources) I get the list of classes that include OtherModule, great! BUT unfortunately it is not able to find a class nested under child module as shown in the #2 example. So I tried doing this :

include_resources = ->(klass) {
        begin
          klass_string = klass.to_s
          klass_resource = klass_string.constantize
          if klass_resource.class == Module
            return "ParentModule::#{klass_string}".constants.find_all do |module_klass|
              module_klass.constantize.included_modules.include?(OtherModule)
            end
          end
          klass_string if klass_resource.included_modules.include?(OtherModule)
        rescue NameError # skip all bad naming and other irrelevant constant loading mishaps
          next
        end
  } 

Unfortunately this returns the same list.

Having two headers with wkhtmltopdf

I have a generated pdf tool that I use. However I've run into a problem in that my header that I have has information about my user, and my user's address. Problem is that there are times where the header gets cut off if the address is two long. So I'm wondering if there is a possibility to have more than one header?

This is what I am trying to do here, however i've still been having some trouble.

  def pdf(admin_fields = false)
    tz = @report.user.address.time_zone || Time.zone.name
    Time.use_zone(tz) do
      html = "<html><head>"

      html << %{<meta name='pdfkit-header_center' content="User: #{@report.user.full_name}, #{@report.user.gender.capitalize}, #{@report.user.birth_date.to_formatted_s(:standard_date)}"> }

      html << %{<meta name='pdfkit-header_center' content="User: # Address: #{@report.user.full_address}"> }

      html << %{<meta name='pdfkit-header_font-size' content="10">}
      html << %{<meta name='pdfkit-header_spacing' content="3">}

      html << '</head><body>'

      html << (I have multiple classes here defined elsewhere in this model)

      html << '</body></html>'
      PDFKit.new(html).to_pdf
    end
  end

With what I have here, it is not creating two lines of headers, instead it is looking at the second address and using that one, and ignoring the first one.

Would anyone know if this is possible to change?

Undefined Method Error in ruby on rails, when trying to produce a nested json format using to_json?

This is the product model in my gems lib s4s models folder:

module S4s
   module Models
     class Product < ActiveRecord::Base
       self.table_name = 'product'
       has_many :images, foreign_key: :product_id, class_name: 'S4s::Models::ProductImage'
       has_many :primary_images, -> { where(primary_image: true) }, foreign_key: :product_id, class_name: 'S4s::Models::ProductImage'
       has_one :image, foreign_key: :product_id, class_name: 'S4s::Models::ProductImage'
       has_many :product_images, foreign_key: :product_id, class_name: 'S4s::Models::ProductImage'
       end
   end
end

This is the product_image.rb file in my gems lib s4s models folder:

require 'paperclip'

module S4s
 module Models
  class ProductImage < ActiveRecord::Base
  self.table_name = 'product_images'.freeze

  include S4s::Models::Concerns::Upload

  TYPE_HIGH_RESOLUTION = 'highResolution'
  TYPE_ADDITIONAL      = 'additional'

  IMAGE_VERSIONS = %w|mini small medium xs sm fullxs fullsm large|

  attr_accessor :image_file_size

  alias_attribute :image_file_name, :original_file_name
  alias_attribute :image_content_type, :file_ext
  alias_attribute :image_updated_at, :updated_at

  belongs_to :product, foreign_key: 'product_id'.freeze, class_name: 'S4s::Models::Product'.freeze
  belongs_to :color, foreign_key: 'color_id'.freeze, class_name: 'S4s::Models::Dictionary::Color'.freeze

  validates :title, presence: true

  scope :additional, -> { where(image_type: TYPE_ADDITIONAL) }
  scope :high_resolution, -> { where(image_type: TYPE_HIGH_RESOLUTION) }
  scope :primary_images, -> { where(primary_image: true) }

  after_initialize :set_default_value
  after_save :set_product_colors!

  add_attachment :image,
                 styles:     {
                     mini:   ['100x100#', :jpg],
                     small:  ['220x220#', :jpg],
                     medium: ['380x380#', :jpg],
                     xs:     ['240x240', :jpg],
                     sm:     ['348x348#', :jpg],
                     fullxs: ['480x480#', :jpg],
                     fullsm: ['768x768#', :jpg],
                     large:  ['1000x1000', :jpg],

                 },
                 path_block: -> (style) { self.build_path(style) },
                 matches:    /(png|jpe?g|gif)/i


  # Populate file_name attribute with the current title
  before_image_post_process :set_file_name!

  public

  def url(type = 'mini')
    return nil unless self.product_id.present?

    image.url(type)
  end

  def urls
    Hash[IMAGE_VERSIONS.map { |v| [v, self.url(v)] }]
  end

  def as_json(opts = {})
    {
        id:               self.id,
        is_primary_image: primary_image?,
        product_id:       self.product_id,
        title:            self.title,
        color:            'n/a',
        sku:              self.sku,
        position:         self.position,
        image_type:       self.image_type,
        urls:             self.urls
    }
  end

  def build_path(style)
    return nil if product.nil?

    build_asset_path(style, !(new_system? || title_used?))
  end

  private

  def build_asset_path(style, old_format = false)
    "/products/#{product_id}/#{build_slug(old_format)}-#{style}.#{_find_extension(image_content_type)}"
  end

  def build_slug(old_format)
    if old_format && !file_name.present?
      "#{product.name.parameterize}#{position > 0 ? "-#{position}" : ''}"
    else
      file_name
    end
  end

  def set_product_colors!
    _colors = self.product.images.map(&:color).compact

    if self.product.colors.map(&:id).sort != _colors.map(&:id).sort
      self.product.update_attribute :colors, _colors
    end
  end

  def set_file_name!
    self.file_name  = SecureRandom.hex(20)
    self.new_system = true
  end

  def set_default_value
    self.position   ||= 0
    self.new_system = true if self.new_system.nil?
  end
  end
 end
end

The Logic is that we are calling these models to different apps using S4s::Models::ModelName

Below is the controller file that I am using to render json(this controller is in another app):

class HalfsController < ApplicationController
    def index
      @hotspot = S4s::Models::Product.all
      render json: @hotspot.to_json(include: :product_images)
    end
    ...
end 

I need a nested format of Product_image objects inside product object. I am New to ruby and rails framework, please help me out.

note: I have tried all format to_json such as :product_images and :product_image.. nested is working for many other models in gems but these are not working for product and product_images.. they have used paperclip to upload and generate images url

MongoMapper - Mongo::OperationFailure - Database command 'update' failed: BSON field 'update.multi' is an unknown field

I am getting Mongo::OperationFailure - Database command 'update' failed: BSON field 'update.multi' is an unknown field. error on MongoMapper set method.

eg: Metadata.set({:cid => 123}, :brand => "b1")

REF: http://ift.tt/pYduRz

I am using following environment:
- Ruby 2.2.0
- Rails 3.2.22
- Gem MongoMapper 0.14.0
- MongoDB 3.6.0

Routing error in ruby rails

So, I am trying to send a GET request from Postman and trying to run the method called question. I am also passing parameters in my request. I keep getting a routing error. Im not sure why. The way I am trying to route it is given below

Rails.application.routes.draw do

namespace 'api' do
 namespace 'v1' do

  get 'questions', to: 'application#/api/v1/question'
  end
 end
end

My questions_controller.rb has a method called question. The file is in app/controllers/api/v1/questions_controller.rb

The error I am getting, Picture of the error I am getting

EDIT. My QuestionController (Shortened version)

module Api
module V1
class QuestionsController < ApplicationController
  def question
    check_args = check_arguments(params[:lower], params[:upper])
    if check_args.is_a?(String)

      render html: "Error"
    else
      lower, upper = check_args
      render json: create_question(lower, upper)
     end
   end
 end
end

XSS prevention in rails input fields?

I have a user input form like

  = simple_form_for(@user) do |f|

    = f.input :about_me, :input_html => {"data-fileupload" => "false", :class => "span12 rich_regular"}, :label => _("about_me")

and the the field about_me is been sanitized at the model level like

  sanitize_text :basic => [:about_me], :except => [:time_zone]

but, when i copy any js script like

  <script>alert(hello)</script>

above alert it is beeing executed i.e, alert is being displayed. how should I prevent it from the front end Kindly help.

link_to, use data for popup, without confirm options

Can it be done without confirm dialog/confirm options - just regular info window.

I'am trying with this...

link_to "Info", customer, remote:true, data: {confirm: "Customer Info:

This shows me choose options, I just want OK button.

mercredi 27 décembre 2017

Puma rails server not starting in Daemon mode on EC-2

I want to run Rails application on EC-2 machine.When my SSH session terminates the rails server shutdown.So i want to run the rails server in the background .I used rails s -d command to run rails daemon mode. But it seems like Puma is not started .This is the message i receive and after that process terminates.

Booting Puma => Rails 5.0.6 application starting in development on http://localhost:3000 => Run rails server -h for more startup options

Usually when i run rails server i get => Booting Puma => Rails 5.0.6 application starting in development on http://localhost:3000 => Run rails server -h for more startup options Puma starting in single mode... * Version 3.11.0 (ruby 2.3.5-p376), codename: Love Song * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://0.0.0.0:3000 Use Ctrl-C to stop

So i guess rails server is not starting..

mardi 26 décembre 2017

How to free a devise route

I'm using gem devise for a project of its own and a question has arisen, how do I leave only one free route, for example I want all other routes to need login and password minus the main page.

I did some research and I got to this link but it did not work out.

Thank you

Association with scope in Ruby on Rails

I have a Ruby on Rails application in which I have licenses, items that can be licensed and a table that lists the two (Which items in what quantity are present in the license?). Analogously to the items in a shopping cart.

Some of the items will no longer be marketed, but I intend to keep them in the database. I then created a soft-delete and used a default scope for the template and for the relationships. But when I try to change existing records using the related template, I get an exception: ActiveRecord :: ReadOnlyRecord

My templates look like this:

class Item <ActiveRecord :: Base
  default_scope {where (deleted: false)}
end

class LicenseItem <ActiveRecord :: Base
  belongs_to: license, touch: true
  belongs_to: item
end

class License <ActiveRecord :: Base
  has_many: license_items,
          -> {joins (: item) .where (items: {deleted: false})},
          dependent:: destroy
end

In this way:

pry (main)> License.find (0) .license_items [0] .readonly?
=> true

Is there any way to make this relationship not just reading?

I have already tried to add readonly (false) at the end of the has_many scope toLicense without success.

jQuery masonry is not working with rails

I am trying to have a transition effect with jQuery masonry in a rails app, for that am using the masonry-rails gem i thing everything has gone well but the masonry effect is not working. My index file

<link href="/assets/lposts.css.scss" rel="stylesheet">
<link href="/assets/lposts.js.coffee" rel="javascript">
<div class="transitions-enabled" id="lposts">
  <% @lposts.each do |lpost| %>
    <div class="box panel panel-default">
      <%= link_to (image_tag lpost.picture.url), lpost %>
      <h2>
        <%= link_to lpost.tittle, lpost %>
      </h2>
      <p class="user">
        Submitted by
        <%= link_to lpost.location, lpost %>
        <center><%= link_to lpost.Contact, lpost %></center>
      </p>
    </div>
  <% end %>
</div>

In my gemfile, i have added the masonry-rails gem

gem 'masonry-rails', '~> 0.2.4'

In my application.js file

// This is a manifest file that'll be compiled into application.js
// 
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// Put JS file that applies to all pages under initializations directory, which
// will get required in init.js.
//
// Put JS file that only applies to a specific page under pages directory, which
// will get required in page_specific.js.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (http://ift.tt/1Hr2XzQ) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require masonry/jquery.masonry
//= require medium-editor
//= require handlebars
//= require jquery-sortable
//= require jquery.ui.widget
//= require jquery.iframe-transport
//= require jquery.fileupload
//= require medium-editor-insert-plugin
//= require index.min
//= require taggle
//= require jquery.autoSave
//= require pubsub
//= require bootstrap-sprockets
//= require react
//= require react_ujs
//= require components
//= require init
//= require page_specific

In my application.scss file

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *= require 'masonry/transitions'
 */




// Use @import to import all Sass files, instead of using sprocket require.
// "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"
@import "bootstrap-sprockets";
@import "bootstrap";
@import "font-awesome-sprockets";
@import "font-awesome";

In my lpost.js.coffee

# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://ift.tt/jEIcxH

 $ ->
   $('#pins').imagesLoaded ->
     $('#pins').masonry
       itemSelector: '.box'
       isFitWidth: true

Issue including a second and a third level association

This query is not working, pease help. I'm trying to include a second and a third deep-level of association.

Pedido > has_one(products_pedido) > has_one(product_size)

@pedidos = Pedido.includes(:pedidos_payments, :products_pedidos => { :product_size } , :estado, :brand, :customer ).where(:is_quote => false)

Ps: I know products_pedido is mispelled according to ActiveRecord good practices :).

Rails - How to add more fields for filter in searchkick?

In rails, I am using searchkick gem for search. When I am adding more fields for where clause then returning zero results.

Actually search is working for below method(User.rb),

searchkick word_start: [:name]

def initialize(name, limit = User::SUGGESTION_LIMIT, page = nil)
  @name = name
  @limit = limit
  @page = page
  @per_page = limit.to_i
end

query = {
    match: :word_start,
    fields: [{ emails: "exact" }, "name^5"],
    misspellings: { prefix_length: 2 },
    load: false
}

User.search(name, query).records

When I add condition like where: {active: false, inactive: true, deleted_at: nil} it returns no data.

query = {
    match: :word_start,
    where: {active: false, inactive: true, deleted_at: nil},
    fields: [{ emails: "exact"}, "name^5"],
    misspellings: { prefix_length: 2 },
    load: false
}

Is there any mistake in above where condition? Please help me to solve this issue. I am using this gem for the first time.

lundi 25 décembre 2017

Holding sending reset password emails until some indecator devise rails

I have a PasswordController inherit from Devise::PasswordsController, I made a create function that helps me to send user reset password notification email, its implementation:

  def create
    # I need to put some condition on the next line
    self.resource = resource_class.send_reset_password_instructions(resource_params)
    if successfully_sent?(resource)
      render :json => "Request successfully sent"
    else
      render :json => resource.errors, :status => 422
    end
  end

It works fine but if user clicked on reset password 5 times 5 emails will be sent to him (If a delay happened or something users never waits, they need fast resposne) and the last one will only work, So I want to disable sending email until this token expired or something, I searched about it but couldn't find anything, I thought about make a new attribute inside user table which will be a datetime to indicate when was the last time the email has been sent but i'm asking if there is a better way to make using devise.

dimanche 24 décembre 2017

Im making a website should i learn Ruby or Ruby on rails?

Hello me and my teacher made a website using ruby on rails, he left of the project and now i want to work on it independently but e problem is that i cant code fully alone he was my instructor, the question is if i should learn ruby on rails cause its a web development coding program or ruby?

vendredi 22 décembre 2017

Rails/Active Admin: redirections on update users reroot to localhost

I'm using Rails 5.1.4 with ActiveAdmin. The admin interface is basic and I haven't customized it a lot. It is used only to managed users on my website (reset passwords in case, ban, add etc.). Otherwise, users are managed by Devise.

I realised that in production, when I try to edit details of an user, I am redirected after the action to https://localhost/admin/users/1 instead of the production url. Adding a new user through the admin interface doesn't work either but I am not sure it is the same issue (just putting this fyi).

I am fairly new to rails and this is actually my first question on StackOverFlow.

Here are my routes:

Rails.application.routes.draw do
  ActiveAdmin.routes(self)
  devise_for :users
  root to: 'pages#home'
  # For details on the DSL available within this file, see http://ift.tt/GVpneB

  get 'my_points', to: 'points#user_points', as: :my_points

  get 'about', to: 'pages#about'

  resources :points do
    member do
      put "/is_featured", to: "points#featured", as: :featured
    end
    resources :reasons, only: [:new, :create]
  end
  resources :services
  resources :topics

  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :topics, only: [ :index, :show ]
      resources :services, only: [ :index, :show ]
      resources :points, only: [ :index, :show ]
    end
  end
end

And my active_admin.rb

ActiveAdmin.setup do |config|
  # == Site Title
  #
  # Set the title that is displayed on the main layout
  # for each of the active admin pages.
  #
  config.site_title = "Phoenix"

  # Set the link url for the title. For example, to take
  # users to your main site. Defaults to no link.
  #
  # config.site_title_link = "/"

  # Set an optional image to be displayed for the header
  # instead of a string (overrides :site_title)
  #
  # Note: Aim for an image that's 21px high so it fits in the header.
  #
  config.site_title_image = "favicon.ico"

  # == Default Namespace
  #
  # Set the default namespace each administration resource
  # will be added to.
  #
  # eg:
  #   config.default_namespace = :hello_world
  #
  # This will create resources in the HelloWorld module and
  # will namespace routes to /hello_world/*
  #
  # To set no namespace by default, use:
  #   config.default_namespace = false
  #
  # Default:
  # config.default_namespace = :admin
  #
  # You can customize the settings for each namespace by using
  # a namespace block. For example, to change the site title
  # within a namespace:
  #
  #   config.namespace :admin do |admin|
  #     admin.site_title = "Custom Admin Title"
  #   end
  #
  # This will ONLY change the title for the admin section. Other
  # namespaces will continue to use the main "site_title" configuration.

  # == User Authentication
  #
  # Active Admin will automatically call an authentication
  # method in a before filter of all controller actions to
  # ensure that there is a currently logged in admin user.
  #
  # This setting changes the method which Active Admin calls
  # within the application controller.
  # config.authentication_method = :authenticate_admin_user!

  # == User Authorization
  #
  # Active Admin will automatically call an authorization
  # method in a before filter of all controller actions to
  # ensure that there is a user with proper rights. You can use
  # CanCanAdapter or make your own. Please refer to documentation.
  # config.authorization_adapter = ActiveAdmin::CanCanAdapter

  # In case you prefer Pundit over other solutions you can here pass
  # the name of default policy class. This policy will be used in every
  # case when Pundit is unable to find suitable policy.
  # config.pundit_default_policy = "MyDefaultPunditPolicy"

  # You can customize your CanCan Ability class name here.
  # config.cancan_ability_class = "Ability"

  # You can specify a method to be called on unauthorized access.
  # This is necessary in order to prevent a redirect loop which happens
  # because, by default, user gets redirected to Dashboard. If user
  # doesn't have access to Dashboard, he'll end up in a redirect loop.
  # Method provided here should be defined in application_controller.rb.
  # config.on_unauthorized_access = :access_denied

  # == Current User
  #
  # Active Admin will associate actions with the current
  # user performing them.
  #
  # This setting changes the method which Active Admin calls
  # (within the application controller) to return the currently logged in user.
  # config.current_user_method = :current_admin_user

  # == Logging Out
  #
  # Active Admin displays a logout link on each screen. These
  # settings configure the location and method used for the link.
  #
  # This setting changes the path where the link points to. If it's
  # a string, the strings is used as the path. If it's a Symbol, we
  # will call the method to return the path.
  #
  # Default:
  config.logout_link_path = :destroy_admin_user_session_path

  # This setting changes the http method used when rendering the
  # link. For example :get, :delete, :put, etc..
  #
  # Default:
  # config.logout_link_method = :get

  # == Root
  #
  # Set the action to call for the root path. You can set different
  # roots for each namespace.
  #
  # Default:
  # config.root_to = 'dashboard#index'

  # == Admin Comments
  #
  # This allows your users to comment on any resource registered with Active Admin.
  #
  # You can completely disable comments:
  # config.comments = false
  #
  # You can change the name under which comments are registered:
  # config.comments_registration_name = 'AdminComment'
  #
  # You can change the order for the comments and you can change the column
  # to be used for ordering:
  # config.comments_order = 'created_at ASC'
  #
  # You can disable the menu item for the comments index page:
  # config.comments_menu = false
  #
  # You can customize the comment menu:
  # config.comments_menu = { parent: 'Admin', priority: 1 }

  # == Batch Actions
  #
  # Enable and disable Batch Actions
  #
  config.batch_actions = true

  # == Controller Filters
  #
  # You can add before, after and around filters to all of your
  # Active Admin resources and pages from here.
  #
  # config.before_action :do_something_awesome

  # == Localize Date/Time Format
  #
  # Set the localize format to display dates and times.
  # To understand how to localize your app with I18n, read more at
  # http://ift.tt/2qUZIMW
  #
  config.localize_format = :long

  # == Setting a Favicon
  #
  config.favicon = 'favicon.ico'

  # == Meta Tags
  #
  # Add additional meta tags to the head element of active admin pages.
  #
  # Add tags to all pages logged in users see:
  #   config.meta_tags = { author: 'My Company' }

  # By default, sign up/sign in/recover password pages are excluded
  # from showing up in search engine results by adding a robots meta
  # tag. You can reset the hash of meta tags included in logged out
  # pages:
  #   config.meta_tags_for_logged_out_pages = {}

  # == Removing Breadcrumbs
  #
  # Breadcrumbs are enabled by default. You can customize them for individual
  # resources or you can disable them globally from here.
  #
  # config.breadcrumb = false

  # == Create Another Checkbox
  #
  # Create another checkbox is disabled by default. You can customize it for individual
  # resources or you can enable them globally from here.
  #
  # config.create_another = true

  # == Register Stylesheets & Javascripts
  #
  # We recommend using the built in Active Admin layout and loading
  # up your own stylesheets / javascripts to customize the look
  # and feel.
  #
  # To load a stylesheet:
  #   config.register_stylesheet 'my_stylesheet.css'
  #
  # You can provide an options hash for more control, which is passed along to stylesheet_link_tag():
  #   config.register_stylesheet 'my_print_stylesheet.css', media: :print
  #
  # To load a javascript file:
  #   config.register_javascript 'my_javascript.js'

  # == CSV options
  #
  # Set the CSV builder separator
  # config.csv_options = { col_sep: ';' }
  #
  # Force the use of quotes
  # config.csv_options = { force_quotes: true }

  # == Menu System
  #
  # You can add a navigation menu to be used in your application, or configure a provided menu
  #
  # To change the default utility navigation to show a link to your website & a logout btn
  #
  #   config.namespace :admin do |admin|
  #     admin.build_menu :utility_navigation do |menu|
  #       menu.add label: "My Great Website", url: "http://ift.tt/1IlgpSu", html_options: { target: :blank }
  #       admin.add_logout_button_to_menu menu
  #     end
  #   end
  #
  # If you wanted to add a static menu item to the default menu provided:
  #
  #   config.namespace :admin do |admin|
  #     admin.build_menu :default do |menu|
  #       menu.add label: "My Great Website", url: "http://ift.tt/1IlgpSu", html_options: { target: :blank }
  #     end
  #   end

  # == Download Links
  #
  # You can disable download links on resource listing pages,
  # or customize the formats shown per namespace/globally
  #
  # To disable/customize for the :admin namespace:
  #
  #   config.namespace :admin do |admin|
  #
  #     # Disable the links entirely
  #     admin.download_links = false
  #
  #     # Only show XML & PDF options
  #     admin.download_links = [:xml, :pdf]
  #
  #     # Enable/disable the links based on block
  #     #   (for example, with cancan)
  #     admin.download_links = proc { can?(:view_download_links) }
  #
  #   end

  # == Pagination
  #
  # Pagination is enabled by default for all resources.
  # You can control the default per page count for all resources here.
  #
  # config.default_per_page = 30
  #
  # You can control the max per page count too.
  #
  # config.max_per_page = 10_000

  # == Filters
  #
  # By default the index screen includes a "Filters" sidebar on the right
  # hand side with a filter for each attribute of the registered model.
  # You can enable or disable them for all resources here.
  #
  # config.filters = true
  #
  # By default the filters include associations in a select, which means
  # that every record will be loaded for each association.
  # You can enabled or disable the inclusion
  # of those filters by default here.
  #
  # config.include_default_association_filters = true

  # == Footer
  #
  # By default, the footer shows the current Active Admin version. You can
  # override the content of the footer here.
  #
  # config.footer = 'my custom footer text'

  # == Sorting
  #
  # By default ActiveAdmin::OrderClause is used for sorting logic
  # You can inherit it with own class and inject it for all resources
  #
  # config.order_clause = MyOrderClause
  def authenticate_admin!
    redirect_to new_user_session_path unless current_user && current_user.admin
  end

  ActiveAdmin.setup do |config|
    config.authentication_method = :authenticate_admin!
    config.current_user_method = :current_user
    config.logout_link_path = :destroy_user_session_path
    config.logout_link_method = :delete
  end
end

Thanks!

jeudi 21 décembre 2017

Rails Devise authentication with email and another field

Using rails with devise. On user table I have email and a field record_status. Record status will contain 'active' or 'deleted'

What do I need to change to authenticate using email and record_status = 'active'.

i have this code in place.

in my user model

def self.find_for_database_authentication(warden_conditions)
  status = 'active'
  where(:email => warden_conditions[:email], :record_status => warden_conditions[:status]).first
end

in my initializer devise.rb

config.case_insensitive_keys = [:email]

thanks for the help guys

Rails/Comment function: undefined method `comment' for nil:NilClass

i want to create a function for comments for my rails application. Therefore only the current_user or an admin (i use active_admin) should be able to delete his comment. But i have trouble to figure that one out because my methods seem to point to nil. can someone help me out please?

My comments_controller.rb

class CommentsController < ApplicationController

before_action :correct_user,   only: :destroy


def create 
    @post =Post.find(params[:post_id])
    @comment =@post.comments.create(params[:comment].permit(:name, :body))
    redirect_to post_path(@post)
end


def destroy 
    @post = Post.find(params[:post_id])
    @comment= @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
end

private

def correct_user
  @user= User.find(current_user.id)
  redirect_to(root_url) unless current_user.id == @post.comment.user.id
end

end

In my correct_user method the undefined comment shows up, so i already tried to add

@post = Post.find(params[:post_id])    
@comment= @post.comments.find(params[:id])

and tried different ways to make this run.

my comment.rb

 class Comment < ApplicationRecord
 belongs_to :post
 end

my post.rb

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy

  validates :title, presence: true, length: {minimum: 5}
  validates :body, presence: true
  validates :user, presence: true
  validates :user_id, presence: true
  has_attached_file :image  #, :styles => { :medium => "300x300>", :thumb => 
  "100x100>" }
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end

and my user.rb

class User < ApplicationRecord
 has_many :posts

 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable  
end

Can someone help me?

PS: i want to do this rather with an before action, then with an if-statement around the delete link.

rails bin/rails generate model rails aborted

i tried running this code,

rails bin/rails generate model Article title:string text:text

but am getting

rails aborted!
Don't know how to build task 'generate' (see --tasks)
bin/rails:4:in `require'
bin/rails:4:in `<main>'
(See full trace by running task with --trace)

I am following the blog documentation line by line and completely installed the ruby buy am still confused why it is not working

please i need help

Rails: How to read a list of images from a URL

I have a URL like below->

images = open("example.com").read

which returns

<center>
<font size=-1>
<img src=http://ift.tt/2pacr2i image<p>
<img src=http://ift.tt/2DkZbKZ image<p>
<img src=http://ift.tt/2pbsflp image<p>
</font>

I want to capture each of these on backend and send them to the front end. So far I was sending the resulting html directly to front end where it was displayed. But now I want to capture it on backend and then send each one to UI. How can I do this?

mercredi 20 décembre 2017

gird view not working in rails

I am really new to rails, i a teaching myself by creating web app, right now am building a pintrest like web app, everything is working nicely, but i want the pints to be in a grid sort of view for that i tried using masonry-rails Gem. But it doesn't seems to work. Here is a ScreenShot of what am getting right now.

My Index file

<link href="/assets/lposts.css.scss" rel="stylesheet">
<link href="/assets/pins.js.coffee" rel="javascript">
<div class="transitions-enabled" id="pins">
  <% @posts.each do |post| %>
    <div class="box panel panel-default">
      <%= link_to (image_tag post.picture.url), post %>
      <h2>
        <%= link_to post.title, post %>
      </h2>
      <p class="user">
        Submitted by
        UserName
      </p>
    </div>
  <% end %>
</div>

My css file

body {
    background: #E9E9E9;
}

h1, h2, h3, h4, h5, h6 {
    font-weight: 100;
}

nav {
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.22);
    .navbar-brand {
        a {
            color: #BD1E23;
            font-weight: bold;
            &:hover {
                text-decoration: none;
            }
        }
    }
}

#pins {
  margin: 0 auto;
  width: 100%;
  .box {
      margin: 10px;
      width: 350px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.22);
      border-radius: 7px;
      text-align: center;
      img {
        max-width: 100%;
        height: auto;
      }
      h2 {
        font-size: 22px;
        margin: 0;
        padding: 25px 10px;
        a {
                color: #474747;
        }
      }
      .user {
        font-size: 12px;
        border-top: 1px solid #EAEAEA;
            padding: 15px;
            margin: 0;
      }
    }
}

#edit_page {
    .current_image {
        img {
            display: block;
            margin: 20px 0;
        }
    }
}

#pin_show {
    .panel-heading {
        padding: 0;
    }
    .pin_image {
        img {
            max-width: 100%;
            width: 100%;
            display: block;
            margin: 0 auto;
        }
    }
    .panel-body {
        padding: 35px;
        h1 {
            margin: 0 0 10px 0;
        }
        .description {
            color: #868686;
            line-height: 1.75;
            margin: 0;
        }
    }
    .panel-footer {
        padding: 20px 35px;
        p {
            margin: 0;
        }
        .user {
            padding-top: 8px;
        }
    }
}

textarea {
    min-height: 250px;
}

** My js file**

# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://ift.tt/jEIcxH

$ ->
  $('#pins').imagesLoaded ->
    $('#pins').masonry
      itemSelector: '.box'
      isFitWidth: true

In my application.scss

*= require 'masonry/transitions'

In my application.js

//= require masonry/jquery.masonry

mardi 19 décembre 2017

How do I shorten a triple Joins ActiveRecord Query with a has_many through relations?

I'm trying to clean up a very long ActiveRecord query. The one I have is working, though it hurts to look at it. Here's what is happening.

1) User has_many Simulations through UserSimulations (and vice versa).

2) User has_many Groups through UserGroups (and vice versa).

3) Group has_many Simulations through SimulationGroups (and vice versa).

What ends up happening here is that a user can be associated to a Simulation in two ways, either directly through the has_many to has_many relationship, or indirectly through a Group that the user belongs to.

I've been able to gather all the Simulations a User has access to in a single query, and it looks like this. I have access to the user (current_user) object where the query needs to be called.

    # Define Queries
    user_sim_join = "LEFT JOIN user_simulations ON user_simulations.simulation_id = simulations.id"
    user_grp_join = "LEFT JOIN user_groups ON user_groups.group_id = groups.id"
    where_clause  = ["user_groups.user_id = :user_id OR user_simulations.user_id = :user_id", { user_id: user.id }]

    # Run Query
    Simulation.joins(user_sim_join, :groups, user_grp_join).where(where_clause).group('simulations.id') 

    => Simulation Load (1.1ms)  SELECT "simulations".* FROM "simulations" 
         INNER JOIN "simulation_groups" ON "simulation_groups"."simulation_id" = "simulations"."id" 
         INNER JOIN "groups" ON "groups"."id" = "simulation_groups"."group_id" 
         LEFT JOIN user_simulations ON user_simulations.simulation_id = simulations.id 
         LEFT JOIN user_groups ON user_groups.group_id = groups.id 
         WHERE (user_groups.user_id = 2 OR user_simulations.user_id = 2) 
         GROUP BY simulations.id

I'm happy that it's working, but would like to clean it up as to be more concise (not 4 lines of code to build a single query).

Thanks!

dimanche 17 décembre 2017

i can't send email using smtp

So i made mailer using

rails g mailer UserMailer

My app/mailers/user_mailer.rb:

class UserMailer < ApplicationMailer
    default from: 'appointments@gmail.com'

    def accepted_appointment(customer)
        @customer = customer
        @user = User.find(@customer.user_id)
        @appointments = @user.appointments.includes(:employee)
        mail(to: @user.email, subject: 'Your appointment has beed accepted')
    end
end

My app/views/accepted_appoitnment.html.erb (I know its a bit empty but i wanted to just send something):

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Hello <%= @customer.first_name %>!</h1>
    <p>

    </p>
    <p>
      Thank you very much for using our services!
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>

And my config/environments/development.rb

Rails.application.configure do
  config.cache_classes = false
  config.eager_load = false
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.active_support.deprecation = :log
  config.active_record.migration_error = :page_load
  config.assets.debug = true
  config.assets.digest = true
  config.assets.raise_runtime_errors = true
  config.action_mailer.default_url_options = { host:
'localhost', port: 3000 }
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.perform_deliveries = true
  config.action_mailer.delivery_method = :smtp
  # SMTP settings for gmail
  config.action_mailer.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :user_name            => "Myemail@gmail.com",
    :password             => "Mypassword",
    :authentication       => "plain",
    :enable_starttls_auto => true
  }
end

And nothing happens. My function where i call accepted_appointment(customer) just doing her work and everything is just great but mail is not sent. What have i done wrong?

vendredi 15 décembre 2017

LoadError (Unable to autoload constant XYZ, expected XYZ.rb to define it) in development environment

Recently, I can't make changes to my app without restarting my development server, otherwise I receive this error:

LoadError (Unable to autoload constant BotFeedback, expected ../../bot_feedback.rb to define it)

This hasn't been a problem before and I'm not entirely sure why this has become a problem. I have these settings configured in application.rb:

# Auto-load the bot and its subdirectories
config.paths.add File.join('app', 'bot'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'bot', '*')]

My app/bot folder includes files such as:

bot.rb with:

require "#{Rails.root}/app/bot/orderbot.rb"
Bot.on :message do |message|
  OrderBot.new()
  ..
end

def somefunction
  OrderBot.new()
  ..
end

orderbot.rb with:

require "#{Rails.root}/app/bot/bot_feedback.rb"
require "#{Rails.root}/app/bot/bot_demo.rb"
require "#{Rails.root}/app/bot/bot_helper.rb"
class OrderBot
  include BotFeedback
  include BotDemo
  include BotHelper
  (many more includes)
  ..
end

bot_feedback.rb with:

require "#{Rails.root}/app/models/concerns/sharedmethods.rb"
class OrderBot
  include Sharedmethods
  module BotFeedback
    ...
  end
end

bot_demo.rb with:

class OrderBot
  module BotDemo
    ..
  end
end

bot_helper.rb with:

require "#{Rails.root}/app/models/concerns/sharedmethods.rb"
class OrderBot
  include Sharedmethods
  module BotHelper
    ...
  end
end

My guess is that including the sharedmethods file is causing this because I don't see anything else being a problem. Changing the sharedmethods file in the rails app has always seemed to require restarting the server.

I would appreciate any help/suggestions.

Rails Rabl gem: query child based on parent id

The rails method:

def index
 user = Users.find(params[:user_id])
 @countries = user.countries
 @cities = user.cities
end

Country model has_many :cities

City model belongs_to :country

User has access to certain countries and certain cities

The corresponding json.rabl file:

object false
child @countries do 
 child @cities.where(country_name: country.name) do
  attributes :name, :coordinates
 end
end

My question is about child @cities.where(country_name: country.name)

My goal is to filter the @cities to only include the cities for the current parent country.

Is this possible in rabl?

How to get the hostname or entire url of the visitor website in Ruby on Rails

If the user clicks a link on http://ift.tt/2CduF4e that points to http://example.com/ the value of request.domain will be example.com

But in my case, I would like to get the visitor's host name facebook.com and entire url http://ift.tt/2CduF4e

How to get that? Any help would be appreciated. Thanks!

jeudi 14 décembre 2017

I'm running rails 3.2.22, and want to install bullet

I'm running rails 3.2.22, and want to install the bullet gem. The latest version doesn't support this old version of rails. I tried installing bullet with older versions around my when rails 3.2.22 was a new, but no luck.

Is this possible? Is there a clever way to figure which version I need?

How to download a xls file from Rails route?

In my AngularJS application, I'm calling a route (from a Rails application) that returns me the contents of a xls file (like below):

<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://ift.tt/qQdaDR">
  <Worksheet ss:Name="Sheet1">
    <Table>
      <Row>
        <Cell><Data ss:Type="String">Ecpm</Data></Cell>
        <Cell><Data ss:Type="String">Total Revenue</Data></Cell>
      </Row>
      .
      .
      .
      <Row>
        <Cell><Data ss:Type="String">4.9</Data></Cell>
        <Cell><Data ss:Type="String">1587.25</Data></Cell>
      </Row>
    </Table>
  </Worksheet>
</Workbook>

The URL is like /api/statistics/earnings/medias_served_export/20171001/20171030.xls

How can I download the file instead of just receive all the text? Should the backend set extra Headers in the route's method?

mercredi 13 décembre 2017

validation with two diffrent objects but same class

So i have this model Appointment:

validates :purpose, :extra, :appointment_date, :appointment_time, presence: true

and now this is situation: i want to get error if someone will want to make appointment in the same day and the same time. So i have to compare two objects of the same class and i have no idea how i can do it.

only one thing comes into my mind

def allready_booked?
  @employee = Employee.find(params[:employee_id]) <----- this is the part i dont know how to do it
  @appointments = Appointment.where(appointment_date: appointment_date).where(employee_id: employee.id)
  @appoitnments.each do |appo|
    if(appo.appointment_date == appointment_date)
      errors.add(:appoitnemnt_date, "is already booked")
    end
  end
end

And yes employee_id is in Appointment model

no mothed for nil after rendering view in controller

So i have this in my view _form.erb

<div class="form-group">
    <%= f.label :start_hour %><br>
    <%= f.select :start_hour, @select_hours.map {|value| [value, value]} %>
</div>

And this in edit.erb

<%= render 'form' %>

And this in my controller

    def edit
        @user = current_user
        @employee = @user.employee
        @hour = @employee.working_hours.find(params[:id])
        @select_hours = Array.new
        for i in 0..12
          @select_hours.push("#{07+i}:00")
          @select_hours.push("#{07+i}:30")
        end
    end

And then my update in my controller

def update
    @employee = current_user.employee
    @hour = @employee.working_hours.find(params[:id])
    if @hour.update(working_hour_params)
      redirect_to employee_working_hours_path(@employee)
    else
      render :edit
    end
end

And here's my problem: when i click update AND have wrong start_hour (custom validation, works when creating not editig) so @hour will not update it renders again this view but with error that there is no method .map for nil (so for @select_hours). So how can i do to fix this?

Ruby get cancel to be button and not link

I have some ruby code to create a basic blog.

I want buttons that allow a user to update or cancel when updating their password. This is in a 'Application Helper'

I want these as buttons but unsure how to make the 'cancel' a button to go back. It is currently just java script and text but the update user is a button.

the code is below

module ApplicationHelper


# Creates a submit button with the given name with a cancel link
  # Accepts two arguments: Form object and the cancel link name
  def submit_or_cancel(form, name='Cancel')
    form.submit + " or " +
      link_to(name, 'javascript:history.go(-1);', :class => 'cancel')
  end
end

mardi 12 décembre 2017

Rails form date_field is showing mm/dd/yyyy

Before I input anything into the rails form. The date_field is showing mm/dd/yyyy.

Is their a way for it to show dd/mm/yyyy.

Placeholder doesn't work.

I have looked around for an answer but none of the answers worked.

Thank you.

Here is the form.

.flex.flex-column.w50p.mx-auto
  = form_for :agreegated_answer, url: survey_aggregated_answers_path(@survey), method: :post  do |f|
    = f.label :procedures_that_have_tags
    = f.collection_select(:tag_ids, @survey.tags, :name, :name, { selected: [] },
      multiple: true, class: 'js-input-tags border-light', placeholder: 'Select tags')
    = f.label :answered_from
    = f.date_field :start_from
    = f.label :answered_to
    = f.date_field :ends_from
    = f.submit 'Generate results'

enter image description here

getting Routing Error on Heroku Server

I am working on rails and locally all the APIs are working fine. Then I have deployed the code to Heroku server, from Heroku server, if I am trying to call any route or URL it shows below error:enter image description here

Local Machine Screenshot:

enter image description here

Redcase Missing Test Cases tab

I have installed redcase plugin, Installation was successful. Redcase is listed in Plugins page. But Test case is not found. I am new to ruby. Any one can help. I have attached plugin page screen shot Plugin Page. But

Installation SASS on mac

After installation command on mac with ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17<br/> 
I have an error like that : <br/>
<"ERROR: While executing gem ... (URI::InvalidURIError) URI must be ascii only "?gems=\u{2013}">


/* Could you help me with that guys, please ??

How can I make the object path / url relate to object name?

I have the object like

class Book
  include Mongoid::Document
  include Mongoid::Timestamps
  field :name, type: String
  field :notes, type: String
end

My url to one of my object when I show it was like http://localhost:3000/coins/5a2e9e460d5fdd0a32153c31

How can I make the url relate to the object name (#{book.name}) like

http://localhost:3000/coins/harrypotter

or

http://localhost:3000/coins/mazerunner

or

http://localhost:3000/coins/coolbook

lundi 11 décembre 2017

You can not call create unless the parent is saved. Help In ruby CODE Fail

I have the following You can not call create unless the parent is saved try saving @p before and enter an infinite save cycle. some idea because I share my code thanks.

    class EncabezadosController < ApplicationController
    files = Dir.glob("#{Rails.root}/lib/oc/*.txt").select do |item| #abre cualquier archivo sin conocer el nombre
  
     next if File.directory? item # busca al siguiente archivo 
     
      
       
    #def   nose 
      File.foreach(item).with_object([]) do |line, result| # recorre el archivo item linea por linea para guardar el encabezado
               puts line    
           

            if line.start_with?('UNH') #leo linea que empiece por UNH
               clave1     =  'ORDEN DE COMPRA'
            end    

              if line.start_with?('BGM')#leo linea que empiece por 
                  clave2     = line[0..2]
                  @codigooc = line[6...26]  
                if line.include?('BGM2') 
                   tipooc = 'ORDEN DE COMPRA '   
                   cajas = line[-1]           
                   else                    
                   tipooc = 'ORDEN DE COMPRA SUGERIDA'
                end
                 if cajas = '1'  
                    @dtipooc = 'CANCELACION'
                end
                if cajas = '9'
                   @dtipooc = 'ORIGINAL'                
                end
                if cajas = '6'
                   @dtipooc = 'PROPUESTA'                        
                end 
            end#line GBM

          if line.start_with?('DTM137')
             fechag2 = Date.new.strftime("%Y/%m/%d")
             clave     = line[0..5]
             fechag = line[6...14]
             @fechag2 = fechag
             @fechag2.unpack('A2A4A2').rotate.join('/')
          end
          if line.start_with?('DTM ')
             fechaen2 = Date.new.strftime("%Y/%m/%d")
             clave    = line[0..2]
             fechaen = line[6...14]
             @fechaen2 = fechaen            
          end
         if line.start_with?('DTM157')# 
            fechalist2 = Date.new.strftime("%Y/%m/%d")
            fechalist = line[6...14]
            @fechalist2 = fechalist 
         end
    
         if line.start_with?('NADBY')              
            clave     = line[0..4]
            @comprador = line[6...-1]#valor original 6..1 modificado por pruebebas              
         end
         if line.start_with?('NADSU')
            clave = line[0..4]
            @proveedor = line[6...-1]       
         end
         #aqui obtengo el nombre de el proveedor
         if line.start_with?('CTAOC') and line.include?('LA VINOTECA LIMITADA') or line.include?('AVDA.MANUEL MONT 1452') or line.include?('3433607')
            clave     = line[0..4]
            @emisor = "LA VINOTECA LIMITADA"          
         end
         #aqui obtengo el nombre del emisor
         if line.start_with?('CTAOC') and !line.include?('LA VINOTECA LIMITADA') and !line.include?('AVDA.MANUEL MONT 1452') and !line.include?('3433607')
            @emisor2 = line[6...-1] 
        

       
         end
         if line.start_with?('PAT')
            clave     = line[0..2]
            @tpago = line[5]
            @tpago2 = @tpago.to_s
            @dias_entrega = line[7..8]  
            @dias_entrega2 = @dentrega.to_s          
            @dias_pagar = line [-3..-1]
            @dpagar2 = @dpagar.to_s
            #result << "#{clave} , codigo #{tpago} , condiciones normales #{tpago} , dias para entrega #{dentrega}  , Dias para pagar #{dpagar} "
         end
         if line.start_with?('TODNC')#tipo flete
            clave     = line[0..4]
            @flete1 = 'flete por cuenta del vendedor sin costo'
         else
            @flete1 = 'flete por cuenta del comprador'        
         end
         if line.start_with?('LOC')
            clave     = line[0..2]
            lugar = line[5]
            codigolugar = line[6...-1]
            @codigolugar2 = codigolugar           
         end
           
        end#do
        #@p = Encabezado.new( numero_oc:@codigooc , tipo_oc:@dtipooc ,                                       fecha_g:@fechag2 , lugar_entrega:@codigolugar2 , inf_comprador:@emisor2 ,  fecha_en: @fechaen2 , fecha_list: @fechalist2 , d_comprador:@comprador , emisor:@emisor, codic_pago:@tpago2 , diascredito:@dpagar , text:@flete1 , diasentrega:@dentrega2)

        #.new luego del ciclo porque necesito generar el vinculo de la tabla     encabezado con detalles
    @p = Encabezado.new( numero_oc: @codigooc , tipo_oc: @dtipooc , fecha_g:     @fechag2 , lugar_entrega: @codigolugar2, inf_comprador: @emisor2, fecha_en: @fechaen2, fecha_list: @fechalist2, d_comprador: @comprador,emisor: @emisor, codic_pago: @flete1, dias_credito: @dpagar, monto_total: @Monototal, dias_entrega:@dentrega2, status_oc: "Inicial")    
          

   File.foreach(item).with_object([]) do |line, result| #recorro la linea del mismo archivo solo para guardar el detalle
       puts "procensando linea #{line} ..."
            case
               
            when line.start_with?('BGM') #numero oc
                  clave2     = line[0..2]
                  @codigooc2 = line[6...26]  

            when line.start_with?('LIN') # indica el numero item y codigo
                @cproducto = line[9..-2]
                @numeroitem = line[7..8]
                @numeroitem2 = @numeroitem.to_s
            when line.start_with?('IMD') #indica la descripcion
                @desproducto = line[8..-1]
            when line.start_with?('QTY 21')  # indica la cantidad pedida y el tipo de unidad de caja                      
                @cantidadpedida = line[19..20]              
                @caja   = line[-3..-1]
                pedido = '?????????????????????'
                when line.start_with?('QTY129') # cantidad de unidades que trae una caja
                @cantidadunidades = line[-6..-4]                               
                @tunidad = 'Unidades Simples'
                #Detalle.last.destroy                        
            when line.start_with?('MOA203') #precio neto del producto               
                @precioneto = line[7..-1] # not [-10..-1
                @precioneto2 = @precioneto.to_f.round(3).to_f              
            when line.start_with?('MOA 204') #monto del descuento pueden haber hasta dos descuentos en una oc               
                @tdescu = 'Descuento'
                @valordescu = line[-10..-1]
            when line.start_with?('PRIAAA') #precio neto de lista de precio por unidad
                pedido = line[-3..-1]
                @valorcd = line[-16..-8]                            
               # @tcaja2  = unitOfMeasure(pedido)
            when (line.start_with?('ALCA') and (line.include?('DE1') or line.include?('DE2')))
                @cdescuento = 'DESCUENTO'              
            when line.start_with?('ALCC') && (line.include?('CA1') || line.include?('CA1'))   
         
                @ccargo = 'CARGO'   
                     
            if line.start_with?('PCD')           
               
                  
                  @porcentaje   = line[-6..-1] # 
                  @porcentaje2   = line[-6..-1]
                  
                  
            end    
             when line.start_with?('MOA 23') #valor en monto del cargo
                  @tcargo = 'Cargo'
                  @valorcargo = line[-10..-1]
         
            when line.start_with?('MOA 86') # monto a pagar total factura
                clave   = line[0..2]              
                importe = line[-9..-1]               
            when line.start_with?('CNT')                             
                @items2 = line[-2..-1]
            else

                puts 'empieza con otra cosa'
            end
  
  

#@p.detalles.create( numero_oc:@codigooc, cod_prod:@cproducto,descrip:@desproducto, numero_item:@numeroitem2, cantidadpedida:@cantidadpedida , precio_unit: @precioneto2 ) 
 @p.detalles.create( numero_oc:@codigooc, cod_prod: @cproducto, descripcion: @desproducto, numero_item: @numeroitem2, cantidad_pedida: @cantidadpedida , precio_unit: @precioneto2 , tipo_caja: @cantidadunidades ,  total_linea: @precioneto2, p_descu1: @porcentaje , monto_descu1: @valordescu, p_descu2: @porcentajedescu2, monto_descu2:"" , p_cargo1:"" , monto_cargo1: @valorcargo)         
       
     end #do
    @p.save
    File.delete(item) if File.exist?(item)
    end #dir
    #borra cada archivo leido para evitar duplicidad

    end #clase
    @p

How do I create a multiple item select list in Rails from database

Greetings

<%= f.collection_select :id, Organisation.order(:Company_Name), :id, :Company_Name, options = {include_blank: "Select an Organisation"}, html_options = {:onchange => 'broadcast_dropdown_change(document.getElementById("broadcast_country_id"), document.getElementById("broadcast_organisation_id"))'} %>

This is my code and its working fine but I want to be able to select multiple Organisations from the database instead of the dropdown list which only allows me one. Please help how I can improve this code to enable it to do so thank you.

dimanche 10 décembre 2017

Rails test error: no such table: files_users: DELETE FROM "files_users"

Hello I am studying rails on ruby and am completely new to coding itself. I apologize in advanced if this is a super easy problem to fix.

I keep getting an error on the following title when I run rails test. I am incorporating fixtures to integration tests and I am quite unsure what these errors mean. If I incorporate test, is there another step to take?

I have 11 errors based on the same but brought one for example:

    Error:
    UserTest#test_name_is_Bob_Builder:
    ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: files_users: DELETE FROM "files_users"


bin/rails test test/models/user_test.rb:12

On my users.yml:

<% salt = BCrypt::Engine.generate_salt %>
<% password = 'abc123' %>

bob:
  name: 'Bob Builder'
  email: 'bob@builder.com'
  password_hash: <%= BCrypt::Engine.hash_secret(password, salt) %>
  password_salt: <%= salt %>

On my user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test 'can create user' do
    before = User.all.size
    User.create
    after = User.all.size

    assert after = before + 1
  end

  test 'name is Bob Builder' do
    user = users(:bob)
    assert user.name == 'Bob Builder'
  end

  test 'can authenticate user' do
    user = User.authenticate('bob@builder.com', 'abc123')
    assert user == users(:bob)
  end
end

No route matches [POST] form not working

I have the following in create_admin.html.erbwhich is located in the directory view/create_admin

<div id="page_wrapper">
    <p>Please insert the usernumber of the user that you want to make admin</p>
    <%= form_tag "/controllers/create_admin_controller" do %>
      <%= text_field_tag "account" %> <br/> <br/>
      <%= submit_tag "Make admin" %>
    <% end %>         
</div>

In the create_admin_controller.rb , I have the following:

def update 
end

In the routes.rb I have the following:

 match "/app/views/createAdmin/create_admin.html.erb" => "create_admin#create_admin", :via => :post, :as => :update

Yet I am getting routing error

No route matches [POST] "/controllers/create_admin_controller"

What am I doing wrong ?

Thanks for your time

Why am I getting Template not found

I have the following routes:

create_admin_path   GET     /app/views/createAdmin/create_admin.html.erb(.:format)  application#createAdmin

I have this in routes.rb

 get "/app/views/createAdmin/create_admin.html.erb", to: "application#createAdmin", as: "create_admin"

I have this in the application_controller.rb

  def createAdmin

  end 

and in the view I have a folder called createAdmin which has a file called create_admin.html.erb

in the create_admin.html.erb I have something like this:

<h1> testing is here </h1>  

Yet I am receiving this error message:

No route matches [GET] "/app/views/create_admin/create_admin.html.erb"

What am I doing wrong ?

Thanks for your time

how to access column using devise user

I added the following columns using a new migration as follows:

class AddDetailsToUser < ActiveRecord::Migration
  def change
    add_column :users, :userNum, :integer
    add_column :users, :username, :string
    add_column :users, :fname, :string
    add_column :users, :surname, :string
    add_column :users, :isTeacher, :boolean, :default => false


  end
end

Now in the application.html.erb I want to do something like this which is trying to show button only when the user is actually a teacher :

<% if @user.isTeacher? %>
                    <div class="buttons">
                        <%= button_to(etc ..) %>
                    </div>
<% end %>

but the problem is that I get the following error message:

undefined method `isTeacher?' for nil:NilClass

How to fix this problem ?

Thanks for your time

samedi 9 décembre 2017

Rails 4 - why my controller action is executes both as html and as json response, as seen in the logs

I have a Rails 4 action with no respond_to block.But in the logs i can see that the action render twice - one for html and other for json.i am wondering whats causing this.

###my route code

get 'halls/:id' => 'home#show_by_location', as: :show_by_location

####my homecontroller code

def show_by_location
 ####logic logic and logic
end

####development/server log

Started GET "/halls/Sydney" for 43.242.228.212 at 2017-12-10 07:28:11 +0000
Cannot render console from 43.242.228.212! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by HomeController#show_by_location as HTML
  Parameters: {"id"=>"Sydney"}

  ########other logs removed.....
  .........
  ...again below is json rendering for same action




Started GET "/halls/[object%20Object]" for 43.242.228.212 at 2017-12-10 07:28:24 +0000
Cannot render console from 43.242.228.212! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by HomeController#show_by_location as JSON
  Parameters: {"id"=>"[object Object]"}

i dont think this is a good sign and this costs my server to process the same data that i really dont need.

Kindly help.

vendredi 8 décembre 2017

Rails Render Index with URL Parameters

Is it possible to render a view and pass along parameters in the url?

def index
  render :index
end

I want this to open up the index page with url parameter (i.e. localhost:4000/users?id=123

I've tried doing something like render :index, id: 123, but that doesn't work. Is the only way to do this via redirect_to?

jeudi 7 décembre 2017

Errno::ENOENT No such file or directory @ rb_sysopen ruby on rails

I have the following problem I get read error There is no such file or directory @ rb_sysopen - abc.txt I marked it in the following line 'File.foreach (item) .with_object ([]) do | line, result | 'Idea idea of why that happens and googled and searched the forum and I do not like a function what some people do. I will comment on that folder if this is said .txt

it's probably a silly mistake but I did not locate it it would be very nice a little help

 Dir.foreach("#{Rails.root}/lib/oc/") do |item|
   next unless File.extname(item) == '.txt'
    next if File.directory? item
   puts item
  File.delete(item) if File.exist?(item)
 end  

Setting up JWT - Passing token from server to client in header, but cannot parse header in client

I am trying to use JWT for user authentication. The client is a React application with Relay. It is talking to a Rails backend through endpoints served by GraphQL.

From the Rails side, I've set up CORS to make sure that I've exposed my header in the response. I've also set my JWT under Authorization:

class Api::GraphsController < ActionController::Base

def create
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
  headers['Access-Control-Max-Age'] = "1728000"
  headers['Access-Control-Expose-Headers'] = 'content-length'

  #set a fresh token after every request
  headers['Authorization'] = "WOW.WoW.Wow"

  render json: Schema.execute()
end

On the React side, I've set up the options in my Relay middleware layer (example from here - http://ift.tt/2ABuL8m). However, this is where I cannot access my header. It just shows Header {} when I print res.headers.

const options = [
  urlMiddleware({
    url: (req) => getEndpoint()
  }),
  retryMiddleware({
    fetchTimeout: 60000,
    retryDelays: (attempt) => [7000],
    forceRetry: (cb, delay) => { window.forceRelayRetry = cb },
    statusCodes: [500, 503, 504]
  }),
  next => req => {
    req.credentials = 'same-origin'; // provide CORS policy to XHR request in fetch method
    const resPromise = next(req);
    resPromise.then(res => {
      let headers = res.headers //Headers is empty
      let user = res.json.data.user //Body is sent properly

      return res;
    })
    .catch((e) => {
      console.log('=============error===========', e);
    })

    return resPromise;
  }
]

When I look in my Chrome's developer tool, I see the Authorization token being set correctly.

Google Inspector

** How do I expose and get the authorization token from my client application? **

Saving images to S3 per bucket or pure Type with Ruby gem

I am just starting to write several images to S3. I will have 4 to 10 images per case per user.

User > Case > images

My plan is to create a bucket per case, but wondering if I should instead save all images with a prefix in the key and have all images for all cases in one bucket?

MyBucket > 2sk67o3/waiver/image1-big.jpg
MyBucket > 2sk67o3/waiver/image1-small.jpg
MyBucket > 2sk67o3/merchandise/image1-big.jpg
MyBucket > 2sk67o3/merchandise/image1-small.jpg

OR

MyBucket_2sk67o3 > waiver/image1-big.jpg
MyBucket_2sk67o3 > waiver/image1-small.jpg
MyBucket_2sk67o3 > merchandise/image1-big.jpg
MyBucket_2sk67o3 > merchandise/image1-small.jpg

I am thinking the last version is correct in that I can use the "with_prefix" provided by the Ruby gem to find images easier to delete or replace them? For instance, to delete the "waiver" I will, of course, want to delete both the big and small image.

bucket.objects.with_prefix('waiver').collect(&:key)

I guess I could just do the first way, above, and search the prefix '2sk67o3/merchandise'. So the question remains better, easier, standard for a bucket per Case or one giant bucket?

mercredi 6 décembre 2017

undefined method `call' for :notifo:Symbol

I have a rails app which is running rails 3.2.22 on Ruby 2.2.5 on Heroku.

I am getting an error which I am having trouble diagnosing;

NoMethodError (undefined method `call' for :notifo:Symbol):

This is the stack trace for it:

vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/deprecation/reporting.rb:13:in `block (2 levels) in warn'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/deprecation/reporting.rb:13:in `each'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/deprecation/reporting.rb:13:in `block in warn'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/deprecation/reporting.rb:12:in `tap'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/deprecation/reporting.rb:12:in `warn'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:212:in `block in clear_stale_cached_connections!'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:210:in `each'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:210:in `clear_stale_cached_connections!'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:274:in `block (2 levels) in checkout'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:242:in `loop'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:242:in `block in checkout'
vendor/ruby-2.2.5/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:239:in `checkout'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:102:in `block in connection'
vendor/ruby-2.2.5/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:101:in `connection'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:410:in `retrieve_connection'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_specification.rb:171:in `retrieve_connection'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_specification.rb:145:in `connection'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/query_cache.rb:67:in `rescue in call'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/query_cache.rb:61:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/callbacks.rb:405:in `_run__1702427010739121446__call__964470083021375166__callbacks'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/callbacks.rb:405:in `__run_callback'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/callbacks.rb:81:in `run_callbacks'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/railties-3.2.22/lib/rails/rack/logger.rb:32:in `call_app'
vendor/bundle/ruby/2.2.0/gems/railties-3.2.22/lib/rails/rack/logger.rb:16:in `block in call'
vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/tagged_logging.rb:22:in `tagged'
vendor/bundle/ruby/2.2.0/gems/railties-3.2.22/lib/rails/rack/logger.rb:16:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/request_store-1.3.2/lib/request_store/middleware.rb:9:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/request_id.rb:22:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/rack-1.4.7/lib/rack/methodoverride.rb:21:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/rack-1.4.7/lib/rack/runtime.rb:17:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/rack-1.4.7/lib/rack/lock.rb:15:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22/lib/action_dispatch/middleware/static.rb:83:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/rack-ssl-1.3.4/lib/rack/ssl.rb:27:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/rack-cache-1.7.1/lib/rack/cache/context.rb:140:in `forward'
vendor/bundle/ruby/2.2.0/gems/rack-cache-1.7.1/lib/rack/cache/context.rb:249:in `fetch'
vendor/bundle/ruby/2.2.0/gems/rack-cache-1.7.1/lib/rack/cache/context.rb:189:in `lookup'
vendor/bundle/ruby/2.2.0/gems/rack-cache-1.7.1/lib/rack/cache/context.rb:66:in `call!'
vendor/bundle/ruby/2.2.0/gems/rack-cache-1.7.1/lib/rack/cache/context.rb:51:in `call'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/railties-3.2.22/lib/rails/engine.rb:484:in `call'
vendor/bundle/ruby/2.2.0/gems/railties-3.2.22/lib/rails/application.rb:231:in `call'
vendor/bundle/ruby/2.2.0/gems/railties-3.2.22/lib/rails/railtie/configurable.rb:30:in `method_missing'
vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.9.4.245/lib/new_relic/agent/instrumentation/middleware_tracing.rb:57:in `call'
vendor/bundle/ruby/2.2.0/gems/puma-3.11.0/lib/puma/configuration.rb:225:in `call'
vendor/bundle/ruby/2.2.0/gems/puma-3.11.0/lib/puma/server.rb:624:in `handle_request'
vendor/bundle/ruby/2.2.0/gems/puma-3.11.0/lib/puma/server.rb:438:in `process_client'
vendor/bundle/ruby/2.2.0/gems/puma-3.11.0/lib/puma/server.rb:302:in `block in run'
vendor/bundle/ruby/2.2.0/gems/puma-3.11.0/lib/puma/thread_pool.rb:120:in `call'
vendor/bundle/ruby/2.2.0/gems/puma-3.11.0/lib/puma/thread_pool.rb:120:in `block in spawn_thread'

To start with the app functions normally, but then after a bunch of requests are made in quick succession this error crops up and then all subsequent requests (which had been working fine before) throw this error and the app crashes.

I can't find any reference to this particular error and I'm rather stumped. The app does not appear to be hitting heroku memory limits so I don't think that is the cause. Could this be a rails 3 issue, or the result of upgrading to rails 3 (from 2)?

Any help on this would be greatly appreciated! thanks.

mardi 5 décembre 2017

rollback transaction error rails

I am trying to create a review form in my rails app but when i click on the submit button, the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:

Google API error: over query limit.
   (0.1ms)  rollback transaction

This is the Reviews Controller:

class ReviewsController < ApplicationController

  # check if logged in
  before_action :check_login, except: [:index, :show]

  def index
    # this is our list page for our reviews
    @price = params[:price]
    @cuisine = params[:cuisine]
    @location = params[:location]


    # start with all the reviews
    @reviews = Review.all

    # filtering by price
    if @price.present?
      @reviews = @reviews.where(price: @price)
    end

    # filter by cuisine
    if @cuisine.present?
      @reviews = @reviews.where(cuisine: @cuisine)
    end

    # search near the location
    if @location.present?
      @reviews = @reviews.near(@location)
    end

  end

  def new
    # the form for adding a new review
    @review = Review.new
  end

  def create
    # take info from the form and add it to the model
    @review = Review.new(form_params)

    # and then associate it with a user
    @review.user = @current_user

    # we want to check if the model can be saved
    # if it is, we're go the home page again
    # if it isn't, show the new form
    if @review.save
      flash[:succces] = "Your review was posted!"

      redirect_to root_path
    else
      # show the view for new.html.erb
      render "new"
    end

  end

  def show
    # individual review page
    @review = Review.find(params[:id])
  end


  def destroy
    # find the individual review
    @review = Review.find(params[:id])

    # destroy if they have access
    if @review.user == @current_user
      @review.destroy
    end

    # redirect to the home page
    redirect_to root_path
  end

  def edit
    # find the individual review (to edit)
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    elsif @review.created_at < 4.hours.ago
      redirect_to review_path(@review)
    end
  end

  def update
    # find the individual review
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    else
      # update with the new info from the form
      if @review.update(form_params)

        # redirect somewhere new
        redirect_to review_path(@review)
      else
        render "edit"
      end
    end
  end

  def form_params
    params.require(:review).permit(:title, :restaurant, :body, :score,
      :ambiance, :cuisine, :price, :address)
  end

end

This is the Review form page:

<%= simple_form_for @review do |f| %>
  <%= f.input :title %>
  <%= f.input :restaurant %>
  <%= f.input :address %>
  <%= f.input :body %>
  <%= f.input :cuisine %>
  <%= f.input :price %>
  <%= f.input :score %>
  <%= f.input :ambiance %>

  <%= f.button :submit %>
<% end %>

The Review Model

class Review < ApplicationRecord

  # add an association that has a 1-to-many relationship
  has_many :comments
  has_many :bookmarks

  # add an association to the user
  belongs_to :user

  geocoded_by :address
  after_validation :geocode


  validates :title, presence: true
  validates :body, length: { minimum: 10 }
  validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
  validates :restaurant, presence: true
  validates :address, presence: true

  def to_param
    id.to_s + "-" + title.parameterize
  end

end

This is My Schema file

  create_table "reviews", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.integer "score"
    t.string "restaurant"
    t.integer "price"
    t.string "cuisine"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "phone_number"
    t.string "ambiance"
    t.text "address"
    t.float "latitude"
    t.float "longitude"
    t.integer "user_id"
  end

multi thread slower than single tread in ruby

I am trying to benchmark the below code,

the method Rate.rate_by_service, does some DB calls / processing and returns a value

mutex = Mutex.new
thread_arr = []
puts Benchmark.measure{
1000.times do |i|
  services.each_with_index do |service_obj,index|
    thread_arr[index] = Thread.new {
      mutex.synchronize {
        rate << Rate.rate_by_service(service_obj,@package,@from,@to,@credentials) #does database calls / calcualtions and returns a value
      }
    }
    #rate << 
  end
  thread_arr.each {|t| t.join}
end
}

The strange thing i have observed is that the multi threaded version is slower that the regular version(without threads)

Here are the benchmarking results.

 #threading
 4.870000   0.490000   5.360000 (  6.846712)
 5.300000   0.520000   5.820000 (  7.550946)
 4.640000   0.480000   5.120000 (  6.720078)
 4.580000   0.460000   5.040000 (  6.344415)
 4.510000   0.450000   4.960000 (  6.312238)




#no threading
3.610000   0.240000   3.850000 (  4.088772)
3.360000   0.200000   3.560000 (  3.721254)
3.380000   0.190000   3.570000 (  3.795252)
3.500000   0.200000   3.700000 (  4.156553)
3.580000   0.210000   3.790000 (  4.183601)

is there something wrong that I am doing? Can anyone please elaborate as to why this behaviour could be happening.

I am using ruby 2.0, rails Rails 4.2.7.1

lundi 4 décembre 2017

rails- convert time to utc based on browser time zone and start_date

I have browser time zone in a cookie variable and date in start_date variable as string . say cookie['browser_zone']="Asia/kolkata" & start_date = "2017/12/31 03:00:00" how can I convert above date to with this time zone to UTC time zone.

helps decipher string and sub-string only for experts

I have the following text I have a decrypted mini manual which is quite limited but recently I decoded a very simile one that I have many problems when going through the file.. the txt is:

UNB+UNOA:2+925485K200:8+78000M0CL0001:1+171128:0356+688'UNH+1+ORDERS:D:96A:UN'BGM+220::9+4450524787+9'DTM+137:20171128:102'DTM+43E:20171201:102'DTM+10:20171128:102'FTX+SPH+++NO PRETICKET'FTX+SPH+++=============================='FTX+SPH+++IF MULTIPLE DESTINATIONS HAVE'FTX+SPH+++THE SAME SHIP DATE, PLEASE 'FTX+SPH+++SHIP TO FURTHEST DESTINATION'FTX+SPH+++FIRST AND CLOSEST DESTINATIONS'FTX+SPH+++LAST.'FTX+SPH+++=============================='RFF+SD:96'RFF+ZZZ:33'RFF+PD:POS REPLEN'NAD+BY+7807900001686::9++DISTRIBUTION CENTER 6009'NAD+SF+++LA VINOTECA S.A.'RFF+IA:003363960'CUX+2:CLP:9'PAT+1++5:3:D:90'TDT+20++30+31+:::UNITED PARCEL'TOD+6+PO'LIN+1++10635818000040:EN'PIA+1+000247791:IN+577670:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO SB BOT 13G'IMD+F++:::VINOSB13G750'QTY+21:15'MOA+203:507240'PRI+AAB:31656::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:32400'TAX+7+VAT:52:ILA+20.50:92'MOA+124:97335'LIN+2++10635818000019:EN'PIA+1+000247797:IN+551540:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CS BOT 13G'IMD+F++:::VINOCS13G750'QTY+21:6'MOA+203:202896'PRI+AAB:31656::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:12960'TAX+7+VAT:52:ILA+20.50:92'MOA+124:38934'LIN+3++10635818000026:EN'PIA+1+000247800:IN+562058:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO MERLOT'IMD+F++:::VINO ME 14 G 750CC'QTY+21:10'MOA+203:338160'PRI+AAB:31656::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:21600'TAX+7+VAT:52:ILA+20.50:92'MOA+124:64890'LIN+4++17809531600020:EN'PIA+1+000252847:IN+1361612:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO SAUVIGNON.'IMD+F++:::VINO 13,5 G 750CC'QTY+21:9'MOA+203:395496'PRI+AAB:41784::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:19440'TAX+7+VAT:52:ILA+20.50:92'MOA+124:77094'LIN+5++10635818000057:EN'PIA+1+000252994:IN+576864:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CS RES BOT13.5G'IMD+F++:::VINOCS13.5G'QTY+21:2'MOA+203:115380'PRI+AAB:55530::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:4320'TAX+7+VAT:52:ILA+20.50:92'MOA+124:22768'LIN+6++10635818000064:EN'PIA+1+000253000:IN+577458:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO MERLOT RESERVA'IMD+F++:::VINO 13,5 G 750CC'QTY+21:5'MOA+203:288450'PRI+AAB:55530::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:10800'TAX+7+VAT:52:ILA+20.50:92'MOA+124:56920'LIN+7++17809531600839:EN'PIA+1+000265725:IN+1880557:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CA RES BOT 14G'IMD+F++:::VINOCA14G750'QTY+21:1'MOA+203:43944'PRI+AAB:41784::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:8566'LIN+8++27808729601174:EN'PIA+1+000270334:IN+3949689:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CS BOT 14G'IMD+F++:::VINOCS14G750'QTY+21:8'MOA+203:264744'PRI+AAB:30933::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:17280'TAX+7+VAT:52:ILA+20.50:92'MOA+124:50728'LIN+9++27808729601181:EN'PIA+1+000287879:IN+3949696:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CA BOT 14G'IMD+F++:::VINOCA14G750'QTY+21:8'MOA+203:264744'PRI+AAB:30933::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:17280'TAX+7+VAT:52:ILA+20.50:92'MOA+124:50728'LIN+10++17804444001193:EN'PIA+1+000406191:IN+3949641:VN'IMD+C+35+CAJ::92'IMD+C+98+750CC::92'IMD+F++:::VINO CA BOT 13G'IMD+F++:::VINOCA13G750'QTY+21:2'MOA+203:67632'PRI+AAB:31656::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:4320'TAX+7+VAT:52:ILA+20.50:92'MOA+124:12978'LIN+11++17804604060015:EN'PIA+1+000419437:IN+5127696:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CA BOT 15G'IMD+F++:::VINOCA15G750'QTY+21:2'MOA+203:76498'PRI+AAB:37169::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:15240'LIN+12++17804604060022:EN'PIA+1+000419438:IN+5127702:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CS BOT 14G'IMD+F++:::VINOCS14G750'QTY+21:4'MOA+203:152996'PRI+AAB:37169::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:4320'TAX+7+VAT:52:ILA+20.50:92'MOA+124:30480'LIN+13++17804319009682:EN'PIA+1+000428549:IN+5108916:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CA RES BOT 14G'IMD+F++:::VINOCA14G750'QTY+21:3'MOA+203:173070'PRI+AAB:55530::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:6480'TAX+7+VAT:52:ILA+20.50:92'MOA+124:34152'LIN+14++17804319009194:EN'PIA+1+000428862:IN+5435739:VN'IMD+C+35+BOT::92'IMD+C+98+375CC::92'IMD+F++:::MERLOT'IMD+F++:::VINO ME 14 G 375CC'QTY+21:2'MOA+203:75898'PRI+AAB:36269::EUP::CA'PAC+24+3'ALC+C+++1'MOA+23:3360'TAX+7+VAT:52:ILA+20.50:92'MOA+124:14870'LIN+15++17804444001346:EN'PIA+1+000465442:IN+5745937:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::MA CHICUREO'IMD+F++:::VINO MA 13.5 G 750CC'QTY+21:1'MOA+203:33816'PRI+AAB:31656::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:6489'LIN+16++27802940730705:EN'PIA+1+000465446:IN+5745975:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CS RES BOT13.5G'IMD+F++:::VINOCS13.5G'QTY+21:19'MOA+203:589285'PRI+AAB:29935::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:20520'TAX+7+VAT:52:ILA+20.50:92'MOA+124:116603'LIN+17++17804611640118:EN'PIA+1+000465449:IN+5746002:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO SB BOT 13.5G'IMD+F++:::VINOSB13.5G'QTY+21:3'MOA+203:153534'PRI+AAB:49018::EUP::CA'PAC+12+3'ALC+C+++1'MOA+23:6480'TAX+7+VAT:52:ILA+20.50:92'MOA+124:30147'LIN+18++15601007001018:EN'PIA+1+000465451:IN+5746064:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::OPORTO TAWNY'IMD+F++:::OPORTO 19.5 G 750CC'QTY+21:1'MOA+203:40260'PRI+AAB:39180::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:1080'TAX+7+VAT:52:ILA+31.50:92'MOA+124:12342'LIN+19++17804606601995:EN'PIA+1+000493788:IN+VINOMEESTA:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO ME ESTATE'IMD+F++:::VINO 14G BOT 750CC'QTY+21:9'MOA+203:100089'PRI+AAB:10041::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:9720'TAX+7+VAT:52:ILA+20.50:92'MOA+124:18522'LIN+20++27802940006022:EN'PIA+1+000517990:IN+POTRODEPIE:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::POTRO DE PIEDRA BLEN'IMD+F++:::VINO 14GR BOT 750CC'QTY+21:1'MOA+203:54526'PRI+AAB:53446::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:1080'TAX+7+VAT:52:ILA+20.50:92'MOA+124:10956'LIN+21++10635818000545:EN'PIA+1+000578874:IN+5125821:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::SANTA EMA AMPLUS CS'IMD+F++:::VINO SB 14 G 750CC'QTY+21:1'MOA+203:109054'PRI+AAB:106894::EUP::CA'PAC+12+3'PAC+1+1'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:21913'LIN+22++17804444001131:EN'PIA+1+000578921:IN+5125715:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::JBOUCHONRESESPMA'IMD+F++:::VINO 13.5 G 750CC'QTY+21:1'MOA+203:62754'PRI+AAB:60594::EUP::CA'PAC+12+3'PAC+1+1'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:12422'LIN+23++17804444001155:EN'PIA+1+000578941:IN+5125722:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CA BOT 13.5G'IMD+F++:::VINOCA13.5G'QTY+21:1'MOA+203:62754'PRI+AAB:60594::EUP::CA'PAC+12+3'PAC+1+1'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:12422'LIN+24++10635818000118:EN'PIA+1+000578968:IN+572224:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CABERNET MERLOT'IMD+F++:::VINO 13.5 G 750CC'QTY+21:3'MOA+203:142686'PRI+AAB:45402::EUP::CA'PAC+12+3'PAC+1+1'ALC+C+++1'MOA+23:6480'TAX+7+VAT:52:ILA+20.50:92'MOA+124:27921'LIN+25++17804625900000:EN'PIA+1+000594393:IN+1:VN'IMD+C+35+BOT::92'IMD+C+98+750CC::92'IMD+F++:::VINO CS BOT 14G'IMD+F++:::VINOCS14G750'QTY+21:2'MOA+203:62028'PRI+AAB:29934::EUP::CA'PAC+6+3'ALC+C+++1'MOA+23:2160'TAX+7+VAT:52:ILA+20.50:92'MOA+124:12272'UNS+S'MOA+86:6067433'CNT+2:25'UNT+281+1'

If you see the only fixed pattern that I see is 'and I see that everything is in a part of the purchase order but I do not know how to go through it letter by letter and when you get it' all that is inside you get it to decipher it .. Any idea is welcome and will be welcomed. I'm new in ruby ​​on rails but I have extensive experience as a developer.

example this one:
BGM+220::9+4450524787+9'
BGM= ORDER TO BUY
220= Type ORDER (TYPE NORMAL or TYPE FULL) but maybe change in other order 
for 
110
9= nothing
4450524787 = # of ORDER TO BUY

I need to do that in each sector but honestly I can not find how to enter it because no pattern is fixed.

i am try if line.include?('BGM')

but without success I try other things but also without success with an idea I am happy with how to enter and if there is a command that allows me to tell what is inside of 'BGM-XXXXXX-XXX' or something like that would be very useful.