samedi 30 septembre 2017

Ruby on rails - constructive way of displaying data

I am new to ruby on rails and JQuery. Still i am in learning stage, In my development i want to display the data in show.html.erb using Jquery i need to fetch and display it when user click the button. I am using AJAX to get the data from the controller method i tried different way to achieve that but for me it is new to debug the issue. Can any one please help.

JQuery Code:

$(document).ready(function()
  {
    $('#patient_list').click(function()
    {
      var key = $("#totalPatient").val();
      $('#patient').empty();
      $("#patient").append("Sample");
      $.ajax(
      {
        type: "GET",
        url: "/show",
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: {'doctor_id': doc_id},
        success: function(result)
        {
          for(term in result)
          {
            render = false;
            $("#patient").append("<p>"+result[term].id"</p>");
          }
        },
        error: function()
        {
          alert("something wrong

!");

        }
      })
    });

Routes

resources :patient_details do
  collection do
    get 'show'
  end
end

patient_details_controller.rb

class PatientDetailsController < ApplicationController
  before_action :set_patient_detail, only: [:show, :edit, :update, :destroy]
  respond_to :json, :html
  def show
    @patient_details  = PatientDetail.where(Doctor_id: params[:doctor_id])
    respond_to do |format|
      format.html
      format.json { render json: @patient_details }  # respond with the created JSON object
    end
  end
end

show.json.jbuilder

json.array!(@patient_details) do |patient|
  json.extract! patient, :id
end

show.html

<div class="table-responsive">
  <table class ="table table-stripe">
    <tbody>
      <div class="form-group">
        <button type="submit" name="patient_list" class="btn btn-info btn-block" id="patient_list"><h6><b>Click here to view the list of patient</b></h6></button>
        <button type="submit" name="patient_list1" class="btn btn-info btn-block" id="patient_list1"><h6><b>Click here to disable the list of patient</b></h6></button>
        <div id="patient"></div>
        <input type="hidden" value="<%= @patient_details.length %>" id="totalPatient">
      </div>
    </tbody>
  </table>
</div>

Any one please give me suggestions about a problem i am facing if possible explain me were i gone wrong with the above code.

Thanks in Advance

Couldn't find template for digesting: spree/store/cart_link

Im doing e-commerce website using spree.when i'am login through the administration section like http://localhost:3000/admin it through an error 'Couldn't find template for digesting: spree/store/cart_link' and also not able to view products and category provided by spree by default.

Anyone can explain rails utility classes or share link in which anyone exlpain rails utility classes in detail

I want to use utility classes in rails.But in rails guide i did not find description about rails utility classes. I don't know how we use in rails. How many types of utility classes and what is the purpose of utility classes.Where it is declared?

jeudi 28 septembre 2017

errors replacing development.sqlite3 with another development.sqlite3 on rails

I am trying out an example from a book head first rails, i get to chapter 2 and i have issues following the instructions maybe because they used an older version of rails.

I am told to replace the development.sqlite3 file with the one provided on the site, and when i do so and try to run the run app again i get errors about pending migrations.

Note:
1. I already ran my migration using rake db:migrate
2. I downloaded the sqlite3 file and replaced the original file.
3. i started the server with rails s command.
4. I reload the page and then i get the error.

ActiveRecord::PendingMigrationError Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development

I have a feeling it has something to do with the schema.rb file? i dunno. I'll really appreciate if someone can help me out here.
I have done my research, i've tried rake db:reset but to no avail. :(

see here: [1]: http://ift.tt/2fAwPWb you can scroll down to the code download section under chapter 2.

access filter model in data base

I start in Ruby and Ruby on rails. I am trying to modify the access to this object (below) in base via the orm and I will like to filter by the values that are in the table node_tags.

def map
......
  nodes = Node.bbox(bbox).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES + 1)
.....
end

probabli on sql requet

SELECT * FROM nodes n INNER JOIN node_tags nt on  n.node_id = nt.node_id where nt.k = 'alert' and nt.v = 'true'

thanks

option selected once in select field. Link adds a new select which should show the remaining options [on hold]

I have a nested form which has a link_to_add which calls a partial having select field .Which have to be changed, option selected once in select field. Link adds a new select which should show the remaining options which are not selected

Adding Spree to Your Rails Application(using getting started spree tutorial)

I am following the spree Documentation

Visit the link

But getting an ERROR -- Could not find gem 'spree (~> 3.1.0) x86-mingw32' in any of the gem sources listed in your Gemfile. Run bundle install to install missing gems.

mercredi 27 septembre 2017

Creating array from dynamic formatted date keys

I'm trying to create a hash that uses the year-month as a key. Consider this code:

(start_date..end_date).map { |date| date.strftime('%Y-%m') }.uniq

The above code creates an array of dates formatted, that looks like below:

["2017-05", "2017-06", "2017-07", "2017-08", "2017-09", "2017-10", "2017-11", "2017-12", "2018-01", "2018-02", "2018-03", "2018-04", "2018-05"]

However, how would you do something similar that would use this formatted date as key with an empty array as value? That looks something like this:

{ "2017-05": [], "2017-06": [], "2017-07": [] ...}

Thanks in advance!

Ruby on Rails Error on Windows 10

How can I solve this problem? please, help. I am using windows 10 and I am trying to run this already existing RoR project.I am very newbie to these projects.

C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-3.2.6/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/mongrel-1.2.0.pre2-x86-mingw32/lib/mongrel.rb:17:in require': cannot load such file -- 2.2/http11 (LoadError) from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/mongrel-1.2.0.pre2-x86-mingw32/lib/mongrel.rb:17:inrescue in ' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/mongrel-1.2.0.pre2-x86-mingw32/lib/mongrel.rb:13:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:91:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:91:in block (2 levels) in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:86:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:86:in block in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:75:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler/runtime.rb:75:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.13.6/lib/bundler.rb:106:inrequire' from C:/bottomup_source/bottomup_source/config/application.rb:7:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands.rb:53:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands.rb:53:in block in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands.rb:50:intap' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-3.2.6/lib/rails/commands.rb:50:in <top (required)>' from script/rails:6:inrequire' from script/rails:6:in `'

C:\bottomup_source\bottomup_source>chown -R user folder 'chown' is not recognized as an internal or external command, operable program or batch file.

mardi 26 septembre 2017

Something's wrong with my gems

Everytime I run gem install something , I get

Successfully installed bundle-0.0.1
ERROR:  While executing gem ... (NoMethodError)
    undefined method `source_paths' for #<Gem::Specification:0x6ab2aec bundle-0.0.1>

I tried to reinstall gem, tried to reinstall bundle/bundler - no help. When I try rails new blog, I get

An error occurred while installing sqlite3 (1.3.13), and Bundler cannot
continue.
Make sure that `gem install sqlite3 -v '1.3.13'` succeeds before bundling.

In Gemfile:
  sqlite3
         run  bundle exec spring binstub --all
Could not find gem 'sqlite3' in any of the gem sources listed in your Gemfile.

What can I do to solve this?

Sort array a by value in array b in Ruby [duplicate]

This question already has an answer here:

I have an array

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

and another array:

b = [0, 3, 6, 3, 4, 0, 1]

Is it possible to sort array a according to values in array b?

The result should be:

a = ['c', 'e', 'b', 'd', 'g', 'a', 'f']

Something like this doesn't seem to exist in Ruby/Rails:

a.sort_with_index{ |elem, index| b[index] }

Understanding rails size vs count, and why .size doesn't work in view?

When I use the method .count, it works just fine and accurately shows the number of posts. When I try .size, it throws an error. Why is this?

My static_controller.rb code (with COUNT as a method)

class StaticController < ApplicationController

def index
@post_count = Post.count
@user_count = User.count
end

index.html.erb (with COUNT as a method)

<div>
      <p> <%= @post_count %> </p>
</div>

When I change the instances of .count to size, I get this error in the local server:

NoMethodError at / undefined method `size' for #

index - app/controllers/static_controller.rb, line 4

Why is this? Is .size not a built in method for rails? If not, how can I fix this issue?

Also, am I correct in understanding that .size is more performant if a counter_cache is applied to the model that the method is being applied to? For example, if my post.rb model has a section where counter_cache is declared, does that automatically make it more fast/performant?

lundi 25 septembre 2017

Rails 3: request is redirected to https even after giving config.force_ssl set to false

my http request is redirected to https even after giving config.force_ssl set to false. I am getting "rack.url_scheme"=>"https", "HTTPS"=>"on"in request object.

vendredi 22 septembre 2017

what's the mean about the rails rspec code`to_not be_valid`?

when i user the ruby on rails to learn how to test a code use the rails rspec,some code i can't understand, here is the code, it is just a code about parking meter test.

db/migrate/xxxxx_create_parking.rb

class CreateParkings < ActiveRecord::Migration[5.0]

def change
    create_table :parkings do |t|
      t.string :parking_type   #guest, short-term, long-term
      t.datetime :start_at   
      t.datetime :end_at     
      t.integer :amount      

      t.integer :user_id, index: true 

app/spec/models/parking_spec.rb

    require 'rails_helper'

RSpec.describe Parking, type: :model do
  #pending "add some examples to (or delete) #{__FILE__}"

 describe ".validate_end_at_with_amount" do

   it "is invalid without amount" do
     parking = Parking.new( :parking_type => "guest",
                            :start_at => Time.now - 6.hours,
                            :end_at => Time.now)
      expect(parking).to_not be_valid
    end

    it "is invalid without end_at" do
      parking = Parking.new( :parking_type => "guest",
                             :start_at => Time.now - 6.hours,
                             :amount => 999)
       expect(parking).to_not be_valid
     end
   end
end

so, what is the mean about the to_not be_valid and t.integer :user_id, index: true ? thanks.

Rack-cors not showing headers in production env for swagger-ui_rails

I'm currently running a couple of Rails 3.2.x apps. The one using Ruby 1.9.x and is the api endpoint has Rack-cors gem (1.0.1) on it - app Alice; the other runs swagger-ui_rails gem and is the app hosting the api documentation -- app Bob. For some reason or another, I cannot get app Alice to give me information for Bob because of this error:

Failed to load http://ift.tt/2xmp7Ga:
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://ift.tt/2fHaFhP' is therefore not allowed access. 

However! When I look on the network tab, the response is a 200 and I can see the json information. But the response headers definitely do NOT have the required Access-Control-Allow-Origin header.

This happens both thru AWS Elastic Beanstalk (Bob is hosted on EBS) and locally (w/ a bound address).

In my config/environments/production.rb of Alice, I have the following:

config.middleware.insert_before 0, 'Rack::Cors' do
  allow do
    origins ->(origin, env) do
      Rails.logger.warn("CORS origin: #{origin}")
      origin =~ /\.example\.com(:\d+)?\z/
    end
    resource('*', :methods => [:get, :post, :options], :headers => :any)
  end
end

When I have this code in config/environments/development.rb in Alice, localhost connects and swagger-ui shows up as expected with no errors in console.

In the network tab of Chrome, this is what I have locally (Bob and Alice in dev/localhost)

Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:http://ift.tt/2xl5AWo
Access-Control-Expose-Headers:
Access-Control-Max-Age:1728000
Content-Length:1499
Content-Type:application/json
Date:Fri, 22 Sep 2017 21:44:45 GMT
Last-Modified:Mon, 28 Aug 2017 17:37:22 GMT
Server:
Vary:Origin

This is what I get for when Bob is in dev and Alice is in prod:

Accept-Ranges:bytes
Connection:keep-alive
Content-Length:1500
Content-Type:application/json
Date:Fri, 22 Sep 2017 23:10:00 GMT
ETag:"abc-559ce64fb8374"
Last-Modified:Fri, 22 Sep 2017 22:04:35 GMT
Server:

As you can see, prod-Alice does not return any sort of headers the way dev-Alice does, even with the exact same Rack-Cors code block.

rake middleware displays Rack::Cors at the top of the stack, and curl -i http://ift.tt/2xmp7Ga has never returned the proper access-control headers for me, both locally and on Bob's server.

prod-Bob also has some EBS extensions to add some request headers and methods to nginx. In some other SO post, I saw folks adding in response headers directly via Rails, and so Bob also has the following in application_controller.rb (and in dev, with binding.pry, I can confirm that the response definitely has the specified headers)

  after_filter :set_access_control_headers

  def set_access_control_headers
    headers['Access-Control-Allow-Origin'] = Rails.configuration.hostnames['headers']
    headers['Access-Control-Request-Methods'] = 'GET, PUT, POST, OPTIONS'
  end

I'm a bit at a loss and any help or thoughts would be appreciated.

OmniAuth with Device, Rails 5 error -"Could not find devise mapping for path"

I have this routes:

Rails.application.routes.draw do
    root to: 'home#index'
    devise_for :user, :path => '', 
    :path_names => { :sign_in => "login", :sign_out => "logout", :sign_up => "registration" }

    match '/auth/:provider/callback', to: 'users/omniauth_callbacks#create', via: [:post, :get]
end

When I try to login, it goes to Twitter page and redirect back, but I see this error:

Could not find devise mapping for path "/auth/twitter/callback?oauth_token=..This may happen for two reasons: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user]

I changed default URLs for login, register and logout with Device. I am using 1 method for all providers. How to set routes to fix this error ?

jeudi 21 septembre 2017

Button doesn't get clicked using capybara (using firefox and xvfb)

I'm trying to set up cucumber tests in docker so I found out that I need to use xvfb in order to at least run tests without GUI. After hours of struggling I've finally run tests, but now:

I'm testing sending data through the form. I'm filling neccessary fields and I'm clicking button, but it doesn't do anything. It works fine when I'm browsing through the page; it is okay when I run cucumber locally without docker (with or without headless firefox), but it fails in that one case. When I'm debugging it sees button, click returning 'ok', but it does nothing. Also current_url doesn't changed and Product is not saved to db (so I assume button does not get clicked).

Could it be problem with not compiled scripts files, maybe javascript doesn't work properly in headless firefox or something else?

Any help would be highly appreciated!

mercredi 20 septembre 2017

how to check the collection_radio_buttons selected for if condition? Rails

I have this form

 <div class="form-group">
      <%= f.label :status %>
        <%= f.collection_radio_buttons(:status, options_for_status, :id, :description) do |b| %>
          <div class="radio">
            <%= b.label { b.radio_button + b.value} %>                
          </div>
          <% end %>
    </div>

    if ??
    #<% f.hidden_field :data_fim, :value => Date.today %>

When the user selects a specific radiobuton, he must execute hiden_field.

STATUS = {:Aguardando => 1, :'Em atendimento' => 2, :Finalizado => 3}

These are the options present for the user, I want to set set date_fim when the user select the radio

:Finalizado => 3

Would JS be my only option? Someone to help a noob in ruby?

I got Fixnum is deprecated when I ran Ruby project

When I run my project, i got these warning. Do you have any idea about that?

Thanks

It has more than 100 rows, i just added one.

C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/watir-webdriver-0.9.9/lib/watir-webdriver/elements/html_elements.rb:17: warning: constant ::Fixnum is deprecated

mardi 19 septembre 2017

Conflict when use validates_format_of for two fields

I very new to the world of Ruby on Rails, but my problem is: when I just type the following code:

validates_format_of :ipaddress, :with => Resolv::IPv4::Regex

It works exactly as I want. But when I do:

validates_format_of :ipaddress, :with => Resolv::IPv4::Regex
validates_format_of :domain, :with => /\A[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}\z/

The tests start to point failures at the IP validation. Why this is happening?

OmniAuth-Facecbook Rails Gem Error

I have this problem with the omniauth-facebook gem the error is

Not found. Authentication passthru.

and here's the logs.

Started GET "/users/auth/facebook" for 127.0.0.1 at 2017-09-19 21:33:14 +0800 Processing by Users::OmniauthCallbacksController#passthru as HTML Rendering text template Rendered text template (0.9ms) Completed 404 Not Found in 14ms (Views: 4.5ms | ActiveRecord: 0.0ms)

here are my gemfiles

gem 'devise'
gem 'omniauth'
gem 'omniauth-facebook'
gem 'sprockets-rails', '~> 3.1', '>= 3.1.1'

My User.rb files

class User < ApplicationRecord
  extend Devise::Models
  acts_as_voter
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook]

  has_one :profile, dependent: :destroy

  has_many :posts, dependent: :destroy # remove a user's posts if his account is deleted.
  has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
  has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy

  has_many :following, through: :active_relationships, source: :followed
  has_many :followers, through: :passive_relationships, source: :follower

  has_many :items, dependent: :destroy

  def self.find_for_oauth(auth)
    user = User.where(uid: auth.uid, provider: auth.provider).first

    unless user
      user = User.create(
        uid:      auth.uid,
        provider: auth.provider,
        email:    User.dummy_email(auth),
        password: Devise.friendly_token[0, 20]
      )
    end

    user
  end

  def self.new_with_session(params, session)
   super.tap do |user|
     if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
       user.email = data["email"] if user.email.blank?
     end
   end
  end

  private

  def self.dummy_email(auth)
    "#{auth.uid}-#{auth.provider}@example.com"
  end
end

my devise.rb files

config.omniauth :facebook, ENV["FB_APP_ID"], ENV["FB_APP_SECRET"]

My OmniauthController files

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    callback_from :facebook
  end

  # def twitter
  #   callback_from :twitter
  # end

  private

  def callback_from(provider)
    provider = provider.to_s

    @user = User.find_for_oauth(request.env['omniauth.auth'])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => provider.capitalize) if is_navigational_format?
    else
      session["devise.#{provider}_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end

lundi 18 septembre 2017

In a Rails 3 many to many association, what is the most efficient way to query objects based on conditions on their associations?

I have a many-to-many model relation:

class Movie
has_many :movie_genres
has_many :genres, :through => :movie_genres

class Genre
has_many :movie_genres
has_many :movies, :through => :movie_genres

class MovieGenre
belongs_to :movie
belongs_to :genre

I want to query all movies with a certain genre but not associated with another genre. Example: All movies that are Action but not Drama.

What I have done is this:

action_movies = Genre.find_by_name('action').movies
drama_movies  = Genre.find_by_name('drama').movies
action_not_drama_movies = action_movies - drama_movies

Is there a more efficient way of doing this? It should be noted that the query can become more complex like: All movies that are Action but not Drama or All movies that are Romance and Comedy

Rails 5 Generate devise with already created user table in PostgreSQL

I know that this may have been asked a lot, but the answers are fuzzy in somways... Basically what i wanna know in a direct way, it's how can i link my table key.tbl_ctrl_usuario with the devise gem...

Devise with rails 5

Adding devise gem to rails 4

These are the links that i check, but the answers i cannot understand completly...

I have my database in Postgresql and my table USER it's declared in this way

CREATE TABLE key.tbl_ctrl_usuario
(
  idusuario integer NOT NULL,
  nombreusuario character varying(150) NOT NULL,
  clave character varying(300) NOT NULL,
  rol character varying(50) NOT NULL,
  estado boolean NOT NULL DEFAULT false,
  CONSTRAINT tbl_ctrl_usuario_pkey PRIMARY KEY (idusuario),
  CONSTRAINT tbl_ctrl_usuario_idusuario_fkey FOREIGN KEY (idusuario)
      REFERENCES key.tbl_ctrl_empleados (idempleado) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);
ALTER TABLE key.tbl_ctrl_usuario
  OWNER TO postgres;

Reload content after JSON response

How can I reload or append the escape javascript file in Json format request in rails.

I am uploading the xls file, and working fine. I wanna to show the uploaded data's as uploaded . but getting json format.

please guide

Add multiple suggestion values in select ruby on rails

<%= f.select :id,
                 lists..collect{|p| [p.name, p.id]} << "add product" ,
                 {prompt:t("select product")}, {:class => "selectpicker"}
    %>

The problem is that add product has added on the last index but i want on second index

dimanche 17 septembre 2017

Adding records to a 'has_many :through' association using a button

This is my first Rails app and have hit another wall. I have a User model and a Country model. They have a many-to-many relationship, which I join together with a Trip model.

A user can maintain a list of countries that they have been to. On the Country page, I want to have a simple bootstrap button so the current_user can add or remove the country to their list.

I am using a partial that looks like the below to at least render buttons on all the pages.

_add_remove_countries.html.erb

<% if @user.countries.exists?(@country.id) %>
    <%= form_for(@user) do |f| %>
      <%= f.submit "Remove Country", class: "btn btn-info" %>
    <% end %>
<% else %>  
    <%= form_for(@user) do |f| %>
      <%= f.submit "Add Country", class: "btn btn-info" %>
    <% end %>
<% end %>

I have tried a few different things, with no luck so I have just reverted to the basic structure. I am currently using a form_for, however that is just what has worked best so far, I am not tied to that solution.

Below are my controllers if needed, I have not set up a Trips controller as I am only using it to join the User and Country Model (maybe I need to set one up?).

users_controller.rb

class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
    @countries = Country.all
  end 

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to @user
    else
      render 'new'
    end
  end

  def update
      redirect_to user_path
  end


  private 

    def user_params
        params.require(:user).permit(:username, :email, :password, :password_confirmation)
    end


end

countries_controller.rb

class CountriesController < ApplicationController

    before_action :require_user, only: [:index, :show]

  def index
    @countries = Country.all
    @sort = CS.countries.sort_by {|key, value| value}
    @sort = @sort.first @sort.size - 2

  end

  def show
    @country = Country.find(params[:id])
    @user = User.find(session[:user_id])
  end

end

rails array with multiple fields

I am trying to create an array that has multiple internal fields so that at the time of rendering I can save the fields of each one, something like this:

@profile = [{module:"user", Description:"module of users"},{module:"products", Description:"module of products"}]

to render and create records this way:

@profile.each do |prof|
    Record.create(module: prof.module, Description: prof.descripcion)
end

but I get this error:

NoMethodError (undefined method `module' for {:module=>"users", :description=>"module of users"}:Hash):
  app/controllers/usuarios_controller.rb:31:in `block in busqueda_usuario_perfil'
  app/controllers/usuarios_controller.rb:30:in `each'
  app/controllers/usuarios_controller.rb:30:in `busqueda_usuario_perfil'

How to set attributes with different names than a DB schema

I am a newbie Ruby developer. I cannot figure out how to create an ActiveRecord model with different attributes names than defined in a DB schema

Consider the following schema

  create_table "sync_tasks", force: :cascade do |t|
    t.string "name"
    t.string "path"
    t.string "task_type"
    t.string "status"
    t.boolean "async", default: false
    t.boolean "direct_download", default: true
    t.datetime "created_at", null: false
    t.datetime "completed_at"
    t.datetime "updated_at", null: false
  end

And I have the following payload

{
    "name" : "Sync /var/www/",
    "path" : "/var/www",
    "directDownload": true,
    "async" : false,
    "taskType" : "directory"
}

And trying to create my model like that

class SyncTask < ApplicationRecord
  TYPE_DB='db'
  TYPE_FILE='file'
  TYPE_DIRECTORY='directory'

  def initialize(params)
 #   super
    @task_type = params[:taskType]
    @direct_download = params[:directDownload]
    @path = params[:path]
    @status = params[:status]
    @async = params[:async]
  end
end

When I try to save it throws an error

<NoMethodError: undefined method `[]' for nil:NilClass>

Also I am not able to access field like that

  new_task = SyncTask.new(allowed_task_params)
  new_task.task_type

It throws the following error

#<NoMethodError: undefined method `task_type' for #<SyncTask not initialized>>

In case I uncomment the super call it gives another error

#<ActiveModel::UnknownAttributeError: unknown attribute 'taskType' for SyncTask.>

What I am doing wrong ? How can I use different attributes names and initialize the model by myself ?

Thanks

samedi 16 septembre 2017

Ruby Model Relationships - Three way Relationship

I have an app that has 3 specific models; User, Country and City. The ideal relationship for each would be as follow:

User

  • has_many :countries
  • has_many :cities, through: :country

Country

  • has_many :users
  • has_many :cities

City

  • has_many :users
  • belongs_to :country

Most of those relationships are fairly straight forward, however, the User-to-City relationship is giving me a bit of a problem. I want to be able to assign a city to a user, as long as the user has been assigned to the country associated to the city. Right now I am not even able to assign a user a city, let alone institute the correct logic for the restriction.

So far what I have been able to read and search has led to the below. Please let me know if you need anything else. Any help is much appreciated!

User.rb

class User < ApplicationRecord

  before_save { self.email = email.downcase}
  #attr_accessible :username, :email
  validates_confirmation_of :password
  has_secure_password

  validates :username, presence: true, length: { maximum: 25 }, uniqueness: {case_sensitive: false}
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }
  validates :password, presence: true, confirmation: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true

  has_many :trips
  has_many :visits, through: :trips
  has_many :countries, through: :trips
  has_many :cities, through: :visits

end

Country.rb

class Country < ApplicationRecord

  has_many :trips
  has_many :cities
  has_many :users, through: :trips

end

City.rb

class City < ApplicationRecord

  has_many :visits
  has_many :users, through: :visits
  belongs_to :country

end

Trip.rb

class Trip < ApplicationRecord

  belongs_to :country
  belongs_to :user
  has_many :visits
  has_many :cities, through: :visits

end

Visit.rb

class Visit < ApplicationRecord

  belongs_to :trip
  belongs_to :city
  has_one :country, through: :city
  has_one :user, through: :trip

end

does not update while pressing update on my articles while editing

My problem is that after i edit the article it reverts back to its old self

these are my pictures representing the steps I took while trying to edit:

before editing : enter image description here

after editing: enter image description here

after pressing the update button: enter image description here

my code:

articles_controller:

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end 

  def new
    @article = Article.new 
  end

  def edit 
    @article = Article.find(params[:id])
  end 

  def update
    @article = Article.find(params[:id])
    if @article.save 
      flash[:notice] = "article was updated"
      redirect_to(@article)
    else
      render 'edit'
    end 
  end 

  def create
    @article = Article.new(article_params)
    if @article.update(article_params)
      flash[:notice] = "Article was submitted succsefully"
      redirect_to (@article)
    else
      render 'new'
    end 
  end

  def show
    @article = Article.find(params[:id])
  end 

  private 

  def article_params 
    params.require(:article).permit(:title, :description)
  end

end 

ask me for more files i f it helps.

P.S. Please don't downvote this question

How to connect RAILS with Red5 Server

I am trying to develop an Application with Red5 Server.

I did some of the steps:

  1. I set up the Red5 server into our local machine (Ubuntu)

  2. I installed the MangoDB database locally with Rails configuration.

  3. Now My problem is: I am using Jruby(Java Ruby) as server programming. I am not able to connect my Rails to Red5 server. Is there any documentation?

vendredi 15 septembre 2017

Create reusable factory for code generation

Currently I have 130 lines of code with similar Ruby code:

@acquirer = create(:acquirer,
                   name: 'OmniPay Datawire acquirer',
                   country_code: 372,
                   timezone: 'Europe/Dublin'
                  )

@reseller = create(:reseller,
                   name: 'OmniPay Datawire reseller',
                   domain: 'op-res-domain')
@merchant = create(:merchant,
                   name: 'OmniPay Datawire Merchant',
                   state_raw: 2,
                   supported_features: 15,
                   merchant_owner: @reseller,
                   login: 'test',
                   pwd: 'test',
                   notification_url: 'http://ift.tt/2xCJGi9')

@contract = create(:contract_supports_all,
                   name: 'Omnipay Datawire Contract',
                   gateway: 'test',
                   mpi: 'test',
                   acquirer: @acquirer,
                   contract_owner: @reseller,
                   merchant: @merchant,
                   descriptor: 'Descriptor',
                   activated: '1',                       
                  )

How I can create factory method for reusing this code?

I would like to save as much as possible space. Can you show me some very useful example which I can use as solution?

rake assets:precompile stuck while deployment after adding rufus-scheduler?

I seem to have the same problem as rake assets:precompile stuck but there's no real solution except for removing rufus-scheduler again.

So, I've installed rufus-scheduler and added this test scheduler

require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.every '5s' do
  puts 'Test1'
end

scheduler.join

and when I deploy, it gets stuck here:

00:16 deploy:assets:precompile
  01 ls /home/user/my-app/releases/20170915094411/assets_manifest_backup
  01 ls: cannot access /home/user/my-app/releases/20170915094411/assets_manifest_backup: No such file or directory
  02 ~/.rvm/bin/rvm ruby-2.3.1@my-app do bundle exec rake assets:precompile
  02 Resque::Helpers will be gone with no replacement in Resque 2.0.0.
  02 /home/essteam/.rvm/rubies/ruby-2.3.1/bin/ruby /home/user/my-app/shared/bundle/ruby/2.3.0/bin/rake assets:precompile:all RAILS_ENV=production RAILS_GROUPS=assets
  02 Resque::Helpers will be gone with no replacement in Resque 2.0.0.
  02 Resque::Helpers will be gone with no replacement in Resque 2.0.0.
  02 Test1
  02 Test1

jeudi 14 septembre 2017

stripe CardError (Cannot charge a customer that has no active card)

def create_charge
 @amount = 500
    customer = Stripe::Customer.create(email: params[:email])
    pay = Stripe::Charge.create(
    :amount => params[:amount],
    :currency =>params[:currency],
    # :source=>params[:token],
    :customer=>customer.id, # obtained with Stripe.js
    :description => "Charge for ")
    send_json_response("Payment","success",{:pay=>pay})
end 

Am trying to create a customer and charge that customer using Rails and Stripe. The customer is getting created in Stripe, but I keep getting the error Cannot charge a customer that has no active card when trying to do the charge

Timing issue in active admin

With in admin panel when I create a new user at 11.00 am as per my local timing is shows user created at 5:47. I found one solution config.time_zone = 'Eastern Time (US & Canada)' and second

before_filter :set_time_zone

private
  def set_time_zone
    Time.zone = current_user.time_zone if current_user
  end

problem with the 1st solution, if admin users are from different time-zones then it will not worked and second solution with in active admin instead of current user current_admin_user available and current_admin_user.time_zone is not working.

mercredi 13 septembre 2017

How to pass argument value to has_one association from method

I have a method in lib folder. Now I need to send a value to has_one which is different model

Example:

lib/acord.rb

def total_pages_of_form_version(form_version)
  form_version.form.check_overflow_form(self.original_effective_date)
end

form.rb

has_one :check_overflow_form, -> (policy_effective_date) { where 'expiration_date >= ? or expiration_date IS NULL', policy_effective_date}, class_name: 'Form', foreign_key: 'parent_form_id', dependent: :destroy

When I run the query, I am getting

Form Load (44.1ms) SELECT forms.* FROM forms WHERE forms.parent_form_id = 18338 AND (expiration_date >= 18338 or expiration_date IS NULL) LIMIT 1

Above query in place of expiration_date it is fetching form_id (18338) but I need to get original_effective_date value

forkmanager fork() function is unimplemented on this machine

when use forkmanager by ruby .it happen this: ruby version: ruby 2.4.1p111 (2017-03-22 revision 58053) [x64-mingw32] system version: windows7 64 Uncaught exception: fork() function is unimplemented on this machine D:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/parallel-forkmanager-2.0.1/lib/parallel/forkmanager.rb:525:in fork' D:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/parallel-forkmanager- 2.0.1/lib/parallel/forkmanager.rb:525:instart'

#!/usr/bin/env ruby
#encoding: UTF-8
# 抓取每一个站点的首页链接数量

require 'rubygems'          
require 'ap'               
require 'json'
require 'net/http'
require 'nokogiri'         
require 'forkmanager'       
require 'beanstalk-client'  

class MultipleCrawler

    class Crawler
        def initialize(user_agent, redirect_limit=1)
            @user_agent = user_agent
            @redirect_limit = redirect_limit
            @timeout = 20
        end
        attr_accessor :user_agent, :redirect_limit, :timeout

        def fetch(website)
            print "Pid:#{Process.pid}, fetch: #{website}\n"
            redirect, url = @redirect_limit, website
            start_time = Time.now
            redirecting = false
            begin
                begin
                    uri = URI.parse(url)
                    req = Net::HTTP::Get.new(uri.path)
                    req.add_field('User-Agent', @user_agent)
                    res = Net::HTTP.start(uri.host, uri.port) do |http|
                        http.read_timeout = @timeout
                        http.request(req)
                    end
                    if res.header['location'] # 遇到重定向,则url设定为location,再次抓取
                        url = res.header['location'] 
                        redirecting = true
                    end
                    redirect -= 1
                end while redirecting and redirect>=0
                opened_time = (Time.now - start_time).round(4) # 统计打开网站耗时
                encoding = res.body.scan(/<meta.+?charset=["'\s]*([\w-]+)/i)[0]
                encoding = encoding ? encoding[0].upcase : 'GB18030'
                html = 'UTF-8'==encoding ? res.body : res.body.force_encoding('GB2312'==encoding || 'GBK'==encoding ? 'GB18030' : encoding).encode('UTF-8') 
                doc = Nokogiri::HTML(html)
                processed_time = (Time.now - start_time - opened_time).round(4) # 统计分析链接耗时, 1.8.7, ('%.4f' % float).to_f 替换 round(4)
                [opened_time, processed_time, doc.css('a[@href]').size, res.header['server']]
            rescue =>e
                e.message  
            end
        end
    end

    def initialize(websites, beanstalk_jobs, pm_max=1, user_agent='', redirect_limit=1)
        @websites = websites                # 网址数组 
        @beanstalk_jobs = beanstalk_jobs    # beanstalk服务器地址和管道参数
        @pm_max = pm_max                    # 最大并行运行进程数
        @user_agent = user_agent            # user_agent 伪装成浏览器访问
        @redirect_limit = redirect_limit    # 允许最大重定向次数

        @ipc_reader, @ipc_writer = IO.pipe # 缓存结果的 ipc 管道
    end

    attr_accessor :user_agent, :redirect_limit

    def init_beanstalk_jobs # 准备beanstalk任务
        beanstalk = Beanstalk::Pool.new(*@beanstalk_jobs)
        #清空beanstalk的残留消息队列
        begin
            while job = beanstalk.reserve(0.1) 
                job.delete
            end
        rescue Beanstalk::TimedOut
            print "Beanstalk queues cleared!\n"
        end
        @websites.size.times{|i| beanstalk.put(i)} # 将所有的任务压栈
        beanstalk.close
        rescue => e 
            puts e 
            exit
    end

    def process_jobs # 处理任务
        start_time = Time.now
        pm = Parallel::ForkManager.new(@pm_max)
        @pm_max.times do |i|
            # 启动后,立刻 next 不会等待进程执行完,这样才可以并行运算
            pm.start(i) and next 
            beanstalk = Beanstalk::Pool.new(*@beanstalk_jobs)
            # 关闭读取管道,子进程只返回数据
            @ipc_reader.close  
            loop{ 
                begin
                    # 检测超时为0.1秒,因为任务以前提前压栈
                    job = beanstalk.reserve(0.1) 
                    index = job.body
                    job.delete
                    website = @websites[index.to_i]
                    result = Crawler.new(@user_agent).fetch(website)
                    @ipc_writer.puts( ({website=>result}).to_json )
                rescue Beanstalk::DeadlineSoonError, Beanstalk::TimedOut, SystemExit, Interrupt
                    break
                end
            }
            @ipc_writer.close
            pm.finish(0)    
        end
        @ipc_writer.close
        begin
             # 等待所有子进程处理完毕 
            pm.wait_all_children 
            # 遇到中断,打印消息      
        rescue SystemExit, Interrupt    
            print "Interrupt wait all children!\n"
        ensure
            results = read_results
             # 打印处理结果
            ap results, :indent => -4 , :index=>false
            print "Process end, total: #{@websites.size}, crawled: #{results.size}, time: #{'%.4f' % (Time.now - start_time)}s.\n"
        end
    end

    def read_results # 通过管道读取子进程抓取返回的数据
        results = {}
        while result = @ipc_reader.gets
            results.merge! JSON.parse(result)
        end
        @ipc_reader.close
        results
    end

    def run # 运行入口
        init_beanstalk_jobs
        process_jobs
    end
end

websites = %w(
http://www.51buy.com/ http://www.360buy.com/ http://www.tmall.com/ http://www.taobao.com/
http://ift.tt/oX2ZfL http://www.paipai.com/ http://shop.qq.com/ http://ift.tt/GRfNbH
http://www.amazon.cn/ http://ift.tt/quKrsm http://www.vancl.com/ http://ift.tt/y9aO1u 
http://ift.tt/IAKFQ5 http://www.m18.com/ http://www.suning.com/ http://www.hstyle.com/
)

beanstalk_jobs = [['127.0.0.1:11300'],'crawler-jobs']
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
pm_max = 10

MultipleCrawler.new(websites, beanstalk_jobs, pm_max, user_agent).run

passing argument in has_one association but not passing value its taking model id

form_version.form.check_overflow_form(self.original_effective_date) Form Load (44.1ms) SELECT forms.* FROM forms WHERE forms.parent_form_id = 18338 AND (expiration_date >= 18338 or expiration_date IS NULL) LIMIT 1

here in palce of 18338 need to pass effective_date, below is my code

form.check_overflow_form(self.original_effective_date)

in form.rb

has_one :check_overflow_form, -> (policy_effective_date) { where 'expiration_date >= ? or expiration_date IS NULL', policy_effective_date}, class_name: 'Form', foreign_key: 'parent_form_id', dependent: :destroy

Please give some solution

mardi 12 septembre 2017

Error In Show And Edit Articles

I have an error when I press show articles and when I press update articles when editing the article. I will show you the image and my code if you think it is not sufficient enough, asking will do just fine.

Image of the show error :

Image of the edit error :

my code :

edit.html.erb:

    <h1>Edit the existing article</h1>
    <% if @article.errors.any? %>
      <h2>The following errors are informing you that if you don't do these then 
      your articles will not be edited</h2>
       <ul>
         <% @article.errors.full_messages.each do |msg| %>
            <li> <%= msg %> </li>
         <% end %>
       </ul>
     <% end %>
       <%= form_for @article do |f| %>
       <p>
         <%= f.label :title %>
         <%= f.text_field:title %>
       </p>
      <p>
         <%= f.label :description  %>
          <%= f.text_area :description %>
       </p>
        <p>
         <%= f.submit %>
      </p>
    <% end %>
    <%= link_to "Back To The List Of Articles", articles_path  %>

show.html.erb:

    <h1>Showing selected articles</h1>

     <p>
         Title: <%= @article.title %>


       </p>
      <p>
          Description: <%= @article.description %>


    </p>

     <%= link_to "Back To The List Of Articles", articles_path  %>
     <%= link_to "Edit This Article", edit_articles_path(@article)  %>

articles_controller :

    class ArticlesController < ApplicationController
     def index

      @articles = Article.all

     end 
       def new
         @article = Article.new 
       end
    def edit 
         @article = Article.find(params[:id])
    end 
     def update 
            @article = Article.find(params[:id])
            if @article.update 
                 flash[:notice] = "article was updated"
                 redirect_to(@article)
           else
                render 'edit'
            end 
     end 
       def create
         @article = Article.new(article_params)
          if @article.save
           flash[:notice] = "Article was submitted succsefully"
            redirect_to (@article)
          else
            render 'new'
           end 
         end
          def show
             @article = Article.find(params[:id])
         end 
         private 
         def article_params 
            params.require(:article).permit(:title, :description)
          end
    end 

index.html.erb

    <h1>ARTICLES</h1>

      <table>

       <tr>

          <th>Title</th>
          <th>Description</th>


      </tr>
       </table>

           <% @articles.each do |article|   %>

    <td><%= article.title %></td>
    <td><%= article.description %></td>
    <td><%= link_to 'Edit', edit_article_path(article) %></td>
    <td><%= link_to 'Show', article_path(article) %></td>
    <% end %>
    <%= link_to "Back To The List Of Articles", articles_path  %>

new.html.erb :

       <h1>Create an article</h1>
     <% if @article.errors.any? %>
    <h2>The following errors are informing you that if you don't do these then 
     your articles will not be created</h2>
      <ul>
         <% @article.errors.full_messages.each do |msg| %>
           <li> <%= msg %> </li>
        <% end %>
      </ul>
    <% end %>
     <%= form_for @article do |f| %>
       <p>
         <%= f.label :title %>
         <%= f.text_field:title %>
       </p>
        <p>
        <%= f.label :description  %>
        <%= f.text_area :description %>
      </p>
       <p>
        <%= f.submit %>
       </p>
    <% end %>
    <%= link_to "Back To The List Of Articles", articles_path  %>   

routes.rb :

    Rails.application.routes.draw do
  # The priority is based upon order of creation: first created -> highest 
priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  # root 'welcome#index'
resources :articles

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


  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: 
product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions 
automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do 
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end

Convert hash keys into a hash in ruby

Please review below input and helps me to convert it into the below output

Input:

[{"Key1"=>1, "key3"=>1}, {"Key2"=>3, "Key4"=>0}, {"Key1"=>1, "Key4"=>1}, {"Key2"=>3, "key3"=>0}, {"Key1"=>3, "Ke5"=>0}]

Output:

[{"Key1"=>1}, {"Key2"=>1}, {"Key3"=>3}, {"Key4"=>0}, {"Key1"=>1}, {"Key4"=>1}, {"Key3"=>3}, {"Key2"=>0}, {"Key1"=>3}, {"Key5"=>0}]

Error Handling - Email LDAP - Rails

I'm beginner in Ruby on Rails and I need help

In my project, I need to catch on LDAP the e-mail of user.

class User < ActiveRecord::Base

 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable and :omniauthable
 devise :ldap_authenticatable,:rememberable, :trackable

 #validates :username, presence: true, uniqueness: true
 validates :email, presence: true
 validates_uniqueness_of :email 
 before_validation :get_ldap_email
 before_save :get_ldap_email

def get_ldap_email
   self.email = Devise::LDAP::Adapter.get_ldap_param(self.username,"mail").first
end

But If in LDAP doesn't have an e-mail, shows an Rails´ error message and I want to redirect to a page with a message made by me.

So, in SessionController i want make an "if", but i don't have success to call the method.

class Users::SessionsController < Devise::SessionsController
require_relative '../../models/User.rb'

def create
 super
 if get_ldap_email == nil
  # redirect to /errorlogin
 end
end

And here show message

undefined local variable or method `get_ldap_email' for # 
Users::SessionsController:0x67342e0>

Also I modificed the User for this...

def get_ldap_email

 ldapEmail =  Devise::LDAP::Adapter.get_ldap_param(self.username,"mail")
 if ldapEmail == nil

 else
  self.email = ldapEmail.first
 end
end

But now show this message

Validation failed: Email can't be blank

I don't what I need to do...

Ruby On Rails Getting SSLError using FCM

Im trying to send a notification to android using Firebase Cloud Messaging i follow the steps, from the site: http://ift.tt/2bqhmC8

However, when i call my controller i always keep getting this error

Started GET "/beneficios/sendNotif?message=Nuevos+beneficios+indexados" for 127.0.0.1 at 2017-09-12 08:49:31 -0600 Processing by BeneficiosController#sendNotif as HTML Parameters: {"message"=>"Nuevos beneficios indexados"} Completed 500 Internal Server Error in 132ms (ActiveRecord: 0.0ms)

OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=error: certificate verify failed):

someone suggest that i need to install the cacert.pem into my enviromental variables, but even with that i keep getting the same error.

This is the method that i call from my controller

def sendNotif
    require 'fcm'
    fcm = FCM.new("AAAA-zAzFEs:APA91bGvID9Rm2oZ6NuNvFD7FJISJcRssNQpnCxe8pkK9oeotzjidy5tDojQKgfPvNFVaS-5f04QO6D7mcs82J4_ittEGa9JH0zNv5eJyYfCSHv--JBFNi3FHU3Ykj-NXatr7bfBaGpz")
    @msg1 = params[:message]
    response = fcm.send_to_topic("BeneficiosCLARO", data: {message: @msg1})
    render json: response
end

Rails call a class from a module

I have a rails 3.2 application where I use differents gem that I have created. I have a folder People and a folder Magazine, so in people I have a file

module Essa::Person
 class CarsDatatable < AjaxDatatablesRails::Base

I want to call CarsDatatable in a external module. How is the syntax to initialize CarsDatatable in a controller of the folder Magazione.

For example i try

CarsDatatable.new

or 

Essa::Person::CarsDatatable

but I have an error

Implement array and interpolate

I have this Ruby code that I want to use:

if args[:remove_existing_trxs] == 'true'
    Acquirer.delete_all
    Company.delete_all
    Currency.delete_all
    AdminUser.delete_all
    BaseReseller.delete_all
    Terminal.delete_all
    Contract.delete_all
    Merchant.delete_all
    MerchantUser.delete_all
    PaymentTransaction.delete_all
  end

How I can define it as an array and interpolate it?

lundi 11 septembre 2017

The passed data is ModelObject::ActiveRecord_Relation, not String Rails 5

Im trying to obtain the id from a table using a where clause, but the value return as an ActiveRecord_Relation.

def generate_qrcode
    idBuscado = get_id_beneficio(3) #the 3 it's just for testing values
    qrcode = make_qrcode(idBuscado)
    send_data qrcode.to_s, type: 'image/png', disposition: 'inline'
  end


private def get_id_beneficio(idBuscado)
    itemlist = Beneficio.select('Id_beneficio', :conditions => ['id_beneficio = ?', "%#{idBuscado}%"]).limit(1)
  end

private def make_qrcode(cadena = 0)
    qrcode = RQRCode::QRCode.new(cadena)
    image = qrcode.as_png(
        resize_gte_to: false,
        resize_exactly_to: false,
        fill: 'white',
        color: 'red',
        size: 300,
        border_modules: 3,
        module_px_size: 4,
        file: nil # path to write
        )
    image.resize(150, 150)
  end

and the error that show... Error

i need to now how to get the value named Id_beneficio and return it as a Integer. Any advice? :(

401 Unauthorized error in rails api-only app when using React

I'm trying to use a rails api-ony app as back-end and React js as front-end. I'm using axios to send/ receive requests. Initially I wasn't able to even login then after much googling I came across this gem it was regarding CORS, it solved my POST request error.
I am able to successfully login when I do POST request in the rails app and I am getting token in return (Which works fine with POSTMAN app). Now, when I do GET request and pass that token as Header using react app it keeps on giving me 401 Unauthorized error, then again after much googling I saw this SO post. It didn't solved the issue. What am I missing? Kindly shed some light about the cause of this issue.
This is application_controller.rb:

class ApplicationController < ActionController::API
    include ActionController::MimeResponds

    before_action :authenticate_request, :current_user, :cors_preflight_check
    attr_reader :current_user

    #before_filter :current_user, :cors_preflight_check
  after_action :cors_set_access_control_headers

# For all responses in this controller, return the CORS access control headers.

def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  if request.method == :options
        headers['Access-Control-Allow-Origin'] = '*'
        headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
        headers['Access-Control-Request-Method'] = '*'
        headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    headers['Access-Control-Max-Age'] = '1728000'
    render :text => '', :content_type => 'text/plain'
  end
end

    require 'date'
            require 'json'
            require 'groupdate'

    @@PRESENT_DATE=Date.parse('2016-12-31T00:00:00.000Z')
    @@MONTHLY_SELECTOR="SELECT CONCAT(MONTHNAME(invoiceDate),' - ',YEAR(invoiceDate)), SUM(invoiceAmt) FROM invoices GROUP BY YEAR(invoiceDate), MONTH(invoiceDate)"
    @@QUARTERLY_SELECTOR="SELECT SUM(invoiceAmt) AS invoiceTotal, CONCAT('Q',QUARTER(invoiceDate), '(', YEAR(invoiceDate), ')') FROM invoices GROUP BY YEAR(invoiceDate), QUARTER(invoiceDate) ORDER BY YEAR(invoiceDate), QUARTER(invoiceDate)"
    @@YEARLY_SELECTOR="SELECT SUM(invoiceAmt) AS invoiceTotal, YEAR(invoiceDate) AS Year FROM invoices GROUP BY YEAR(invoiceDate) ORDER BY YEAR(invoiceDate)"

    private

    def authenticate_request
        @current_user = AuthorizeApiRequest.call(request.headers).result
        render json: { error: 'Not Authorized' }, status: 401 unless @current_user
    end
end

In my react app I have this:

import React, { Component } from 'react';
import '../App.css';
var axios = require('axios');

class Login extends Component {
  constructor(props){
    super(props);
    //this.state = {isToggleOn: true};
    this.loadDashboard = this.loadDashboard.bind(this);
    this.handleOnSubmit = this.handleOnSubmit.bind(this);
  }

  loadDashboard(token){
    axios({
      method:'get',
      url:'http://localhost:3000/api/dashboard',
      data: {
        Authorization: token,
      },
    })
     .then(function (response) {
       console.log(response);
     })
     .catch(function (error) {
       console.log("Error in loading Dashboard "+error.response.status);
     });
  }

  handleOnSubmit = () => {
     console.log("submittwed");
     axios({
       method:'post',
       url:'http://localhost:3000/authenticate',
       data: {
         email: 'test@mail.com',
         password: 'apple'
       },
     })
      .then((response) => {
        var token = response.data.auth_token;
        console.log(token);
        this.loadDashboard(token);
      })
      .catch(function (error) {
        console.log("Error in login "+error);
      });
   }

  render() {
    return (
      <div>
         Username: <input type="email" name="fname" /><br />
         Password: <input type="password" name="lname" /><br />
         <button onClick={this.handleOnSubmit}>LOG IN</button>
      </div>
    );
  }
}

export default Login;

  • Did any one else faced something similar??
  • How do I solve this?
  • Is there any less messy/better approach?

Please help me to solve this.

Favourite Model #No route match

I got this error

No route matches {:action=>"favorite", :controller=>"microposts", :id=>#, :type=>"favorite"} missing required keys: [:id]

Models:

class User< ApplicationRecord  
  has_many :microposts,dependent: :destroy
  has_many :favorite_microposts
  has_many :favorites, through: :favorite_micoposts, source: :micropost    
end

class Micropost < ApplicationRecord  
  has_many :favorite_microposts
  has_many :favorited_by, through: :favorite_microposts, source: :user
end         


class FavoriteMicropost < ApplicationRecord
  belongs_to :user
  belond_to :micropost
end

Micropost Controller:

class MicropostsController < ApplicationController
...
def favorite
 @micropost = Micropost.find(params[:id])  
 type = params[:type]
 if type == "favorite"
   current_user.favorites << @micropost
   redirect_to :back, notice: 'You favorited #{@micropost.number}'

 elsif type == "unfavorite"
   current_user.favorites.delete(@micropost)
   redirect_to :back, notice: 'Unfavorited #{@micrpost.number}'

 else
   # Type missing, nothing happens
   redirect_to :back, notice: 'Nothing happened.'
   end
  end
 end

Routes:

Rails.application.routes.draw do
resources :microposts do  
    match :favorite, on: :member, via: [:put, :delete]
  end
end

View:

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

Pass parameter to Validation - Rails 3

We are currently valid different sections via the following code:

on_boarding_form.rb

  def valid?
    @sections.all? {|section| section.valid?}
  end

This goes to on_boarding_section_form.rb. Where we do some checks

  validate do
    @fields.where(:required => true).where(:hidden => false).each do |req_field|

      if req_field.name.to_s == 'FAVOR'
        binding.remote_pry
      end

      if defined? land1
        if land1 == 'BE' && req_field.name.to_s == 'ORT01'
          # do nothing
        elsif land1 == 'BE' && req_field.name.to_s == 'ENTK2'
          # do nothing
        elsif land1 == 'BE' && req_field.name.to_s == 'PSTLZ'
          #validate postal code
          @errors.add_on_blank(req_field.name.downcase.to_sym)
        elsif land1  != 'BE' && req_field.name.to_s == 'ORT01'
          @errors.add_on_blank(req_field.name.downcase.to_sym)
        elsif land1  != 'BE' && req_field.name.to_s == 'ENTK2'
          @errors.add_on_blank(req_field.name.downcase.to_sym)
        elsif land1  != 'BE' && req_field.name.to_s == 'PSTLZ'
          # do nothing
        else
          @errors.add_on_blank(req_field.name.downcase.to_sym)
        end
      else
        @errors.add_on_blank(req_field.name.downcase.to_sym)
      end
    end
    @fields.where(:hidden => false).each do |field|
      next if field.field_type =~ /g/i
      next if field.field_type =~ /d/i
      next if field.field_type =~ /p/i
      validates_with LengthValidator, :attributes => field.name.downcase.to_sym, :in => 0..field.field_length
    end
  end

In sections emergency contact we need to check if the person is married or not. If the person is married the emergency contact fields should be required.

Now my question is in on_boarding_form.rb is possible to pass a parameter to on_boarding_section_form.rb so I can pass the marital status.

Thank you!

Kind regards, Vincent

dimanche 10 septembre 2017

Was able to view the rails start page after 'rails server', but unable to now on cloud9

I've tried to search for the answer to my question but couldn't find it. Apologies if this has been answered already.

So I've been doing a Ruby on Rails course from Udemy, and after create an application, I decided to start from the beginning and recreating the application.

lol, I got stuck right at step one :(

So I went to my cloud9, went to my terminal where my rails projects were and created a new rails project rails new myApp

Afterwards, I went into it cd myApp, then ran rails server

I noticed before, it would say webBRICK, but now it says puma

Also, I get this:

=> Booting Puma => Rails 5.1.4 application starting in development => Run ' rails server -h ' for more startup options Puma starting in single mode... * Version 3.10.0 (ruby 2.4.1-p111), codename: Russell's Teapot * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://localhost:8080 Use Ctrl-C to stop

Usually, at the end of the 2nd line, there is in development http://localhost:3000 But I'm not getting that at all now.

I can't even go to the page to see that default rails page. I've even tried manually entering it in with no luck.

So I'm just wondering, is there something I've done to change things?

I've tried multiple things.

rails s -p $PORT -b $IP', 'killall ruby, creating a new workspace

Sadly none of these or other solutions have worked. It's annoyed me as I was able to see the rails page I made before but now, nothing happens/just can't even find the rails page.

(The course I did installed Heroku and github credentials. I'm currently on a new workspace in cloud9).

Just wondering if there is anything else I can try?

Thanks

samedi 9 septembre 2017

error while trying to see articles

I am getting this error while going into articles/new

enter image description here

my code :

new.html.erb :

<h1>Create an article</h1>
<%if @article.error.any? %>
<ul>
    <% @article.errors.full_messages.each do |msg| %>
    <li> <%= msg %> </li>
</ul>



<%= form_for @article do |f| %>

<p>
    <%= f.label :title %>

    <%= f.text_field:title %>

</p>
<p>
    <%= f.label :description  %>
    <%= f.text_area :description %>

</p>
<p>
    <%= f.submit %>

</p>
    end

my articles_controller.erb file :

class ArticlesController < ApplicationController

   def new
     @article = Article.new 
   end

   def create
     @article = Article.new(article_params)
     if  @article.save
       flash[:notice] = "Article was submitted succsefully"
       redirect_to (@article)
     else
       render :new
     end 
   end

    private 
    def article_params 
       params.require(:article).permit(:title, :description)
    end
end 

ask me for any other files if it helps

vendredi 8 septembre 2017

Rails Cancan NameError - uninitialized constan

Hi, I need your help with cancan.

I have this controler:

class RegistrationsController < Devise::RegistrationsController

I needed because I had to overwrite some methods.

I need to control the access to this controller because the administrator is the only that can add a new user.

How can I use load_and_authorize_resource?

My ability.rb file is: class Ability include CanCan::Ability

def initialize(user, controller_namespace) user ||= Usuario.new

case controller_namespace
  when "Administrator"
    if user.rol == 1    
        can :manage, Faq
        can :manage, Tip
        can :manage, Administrator::HomeTratamientoController
   end
    if user.rol == 2
        can :manage, :admin_vacunas
        can :manage, Registration
    end
  when "paciente"
    if user.rol == 3
        can :manage, Paciente::HomeController
    end
  else  
        can :read, :all
 end 

end

The model is usuario.rb

I don't have problem when the rol is 1 but when is 2, and I put the line:

load_and_authorize_resource

when in the registration controller I call the action new to add a new user by the adminstrator, show me the follow error:

Completed 500 Internal Server Error in 42ms (ActiveRecord: 5.1ms)

NameError - uninitialized constant Registration: activesupport (4.2.1) lib/active_support/dependencies.rb:533:in load_missing_constant' activesupport (4.2.1) lib/active_support/dependencies.rb:184:inconst_missing' activesupport (4.2.1) lib/active_support/inflector/methods.rb:261:in block in constantize' activesupport (4.2.1) lib/active_support/inflector/methods.rb:259:inconstantize' activesupport (4.2.1) lib/active_support/core_ext/string/inflections.rb:66:in constantize' cancancan (2.0.0) lib/cancan/controller_resource.rb:156:inresource_class' cancancan (2.0.0) lib/cancan/controller_resource.rb:192:in resource_base' cancancan (2.0.0) lib/cancan/controller_resource.rb:80:inbuild_resource' cancancan (2.0.0) lib/cancan/controller_resource.rb:61:in load_resource_instance' cancancan (2.0.0) lib/cancan/controller_resource.rb:35:inload_resource' cancancan (2.0.0) lib/cancan/controller_resource.rb:12:in block in add_before_action' activesupport (4.2.1) lib/active_support/callbacks.rb:448:inblock in make_lambda' activesupport (4.2.1) lib/active_support/callbacks.rb:164:in block in halting' activesupport (4.2.1) lib/active_support/callbacks.rb:504:inblock in call' activesupport (4.2.1) lib/active_support/callbacks.rb:504:in call' activesupport (4.2.1) lib/active_support/callbacks.rb:92:in_run_callbacks' activesupport (4.2.1) lib/active_support/callbacks.rb:776:in _run_process_action_callbacks' activesupport (4.2.1) lib/active_support/callbacks.rb:81:inrun_callbacks' actionpack (4.2.1) lib/abstract_controller/callbacks.rb:19:in process_action' actionpack (4.2.1) lib/action_controller/metal/rescue.rb:29:inprocess_action' actionpack (4.2.1) lib/action_controller/metal/instrumentation.rb:32:in block in process_action' activesupport (4.2.1) lib/active_support/notifications.rb:164:inblock in instrument' activesupport (4.2.1) lib/active_support/notifications/instrumenter.rb:20:in instrument' activesupport (4.2.1) lib/active_support/notifications.rb:164:ininstrument' actionpack (4.2.1) lib/action_controller/metal/instrumentation.rb:30:in process_action' actionpack (4.2.1) lib/action_controller/metal/params_wrapper.rb:250:inprocess_action' activerecord (4.2.1) lib/active_record/railties/controller_runtime.rb:18:in process_action' actionpack (4.2.1) lib/abstract_controller/base.rb:137:inprocess' actionview (4.2.1) lib/action_view/rendering.rb:30:in process' actionpack (4.2.1) lib/action_controller/metal.rb:196:indispatch' actionpack (4.2.1) lib/action_controller/metal/rack_delegation.rb:13:in dispatch' actionpack (4.2.1) lib/action_controller/metal.rb:237:inblock in action' actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:74:in dispatch' actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:43:inserve' actionpack (4.2.1) lib/action_dispatch/routing/mapper.rb:49:in serve' actionpack (4.2.1) lib/action_dispatch/journey/router.rb:43:inblock in serve' actionpack (4.2.1) lib/action_dispatch/journey/router.rb:30:in serve' actionpack (4.2.1) lib/action_dispatch/routing/route_set.rb:819:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' newrelic_rpm (3.16.1.320) lib/new_relic/rack/agent_hooks.rb:30:intraced_call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' newrelic_rpm (3.16.1.320) lib/new_relic/rack/browser_monitoring.rb:32:intraced_call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' newrelic_rpm (3.16.1.320) lib/new_relic/rack/developer_mode.rb:48:intraced_call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' warden (1.2.6) lib/warden/manager.rb:35:inblock in call' warden (1.2.6) lib/warden/manager.rb:34:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/etag.rb:24:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/conditionalget.rb:25:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/head.rb:13:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' actionpack (4.2.1) lib/action_dispatch/middleware/params_parser.rb:27:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' actionpack (4.2.1) lib/action_dispatch/middleware/flash.rb:260:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/session/abstract/id.rb:225:in context' rack (1.6.4) lib/rack/session/abstract/id.rb:220:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' actionpack (4.2.1) lib/action_dispatch/middleware/cookies.rb:560:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' activerecord (4.2.1) lib/active_record/query_cache.rb:36:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' activerecord (4.2.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:649:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' activerecord (4.2.1) lib/active_record/migration.rb:378:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' actionpack (4.2.1) lib/action_dispatch/middleware/callbacks.rb:29:inblock in call' activesupport (4.2.1) lib/active_support/callbacks.rb:88:in _run_callbacks' activesupport (4.2.1) lib/active_support/callbacks.rb:776:in_run_call_callbacks' activesupport (4.2.1) lib/active_support/callbacks.rb:81:in run_callbacks' actionpack (4.2.1) lib/action_dispatch/middleware/callbacks.rb:27:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' actionpack (4.2.1) lib/action_dispatch/middleware/reloader.rb:73:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' actionpack (4.2.1) lib/action_dispatch/middleware/remote_ip.rb:78:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' better_errors (2.1.1) lib/better_errors/middleware.rb:84:inprotected_app_call' better_errors (2.1.1) lib/better_errors/middleware.rb:79:in better_errors_call' better_errors (2.1.1) lib/better_errors/middleware.rb:57:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' actionpack (4.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' web-console (2.3.0) lib/web_console/middleware.rb:28:inblock in call' web-console (2.3.0) lib/web_console/middleware.rb:18:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' actionpack (4.2.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' railties (4.2.1) lib/rails/rack/logger.rb:38:in call_app' railties (4.2.1) lib/rails/rack/logger.rb:20:inblock in call' activesupport (4.2.1) lib/active_support/tagged_logging.rb:68:in block in tagged' activesupport (4.2.1) lib/active_support/tagged_logging.rb:26:intagged' activesupport (4.2.1) lib/active_support/tagged_logging.rb:68:in tagged' railties (4.2.1) lib/rails/rack/logger.rb:20:incall' quiet_assets (1.1.0) lib/quiet_assets.rb:27:in call_with_quiet_assets' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' actionpack (4.2.1) lib/action_dispatch/middleware/request_id.rb:21:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/methodoverride.rb:22:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/runtime.rb:18:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' activesupport (4.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/lock.rb:17:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' actionpack (4.2.1) lib/action_dispatch/middleware/static.rb:113:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' rack (1.6.4) lib/rack/sendfile.rb:113:in call' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:incall' railties (4.2.1) lib/rails/engine.rb:518:in call' railties (4.2.1) lib/rails/application.rb:164:incall' newrelic_rpm (3.16.1.320) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in call' rack (1.6.4) lib/rack/content_length.rb:15:incall' thin (1.7.0) lib/thin/connection.rb:86:in block in pre_process' thin (1.7.0) lib/thin/connection.rb:84:inpre_process' thin (1.7.0) lib/thin/connection.rb:53:in process' thin (1.7.0) lib/thin/connection.rb:39:inreceive_data' eventmachine (1.2.0.1) lib/eventmachine.rb:194:in run' thin (1.7.0) lib/thin/backends/base.rb:73:instart' thin (1.7.0) lib/thin/server.rb:162:in start' rack (1.6.4) lib/rack/handler/thin.rb:19:inrun' rack (1.6.4) lib/rack/server.rb:286:in start' railties (4.2.1) lib/rails/commands/server.rb:80:instart' railties (4.2.1) lib/rails/commands/commands_tasks.rb:80:in block in server' railties (4.2.1) lib/rails/commands/commands_tasks.rb:75:inserver' railties (4.2.1) lib/rails/commands/commands_tasks.rb:39:in run_command!' railties (4.2.1) lib/rails/commands.rb:17:in' bin/rails:9:in <top (required)>' spring (1.7.2) lib/spring/client/rails.rb:28:incall' spring (1.7.2) lib/spring/client/command.rb:7:in call' spring (1.7.2) lib/spring/client.rb:30:inrun' spring (1.7.2) bin/spring:49:in <top (required)>' spring (1.7.2) lib/spring/binstub.rb:11:in' bin/spring:13:in <top (required)>' bin/rails:3:in'

Some body can help me please?

jeudi 7 septembre 2017

getting error while creating Web services with Ruby on Rails

Getting error while creating webservices on ruby on rails.

i have followed what ever the steps mentioned in this url. http://ift.tt/2vKwkvo

After starting the Server with rails s command, when i am hitting http://localhost:3000/hello_message/wsdl this url, its giving me the error as "ActionController::RoutingError (No route matches [GET] /hello message/wsdl):"

Please help me to resolve the issue.

Thanks, Jitender

Check if user has restaurant 48hours after sign up

I have some trouble to check if my user have created a restaurant 48 hours after signed_up ( the objective is to send an Email reminder).

I tried differents things and right now i'm with this in my

USER MODEL : User.rb

after_create :reminder



def reminder
    if Time.now.utc == self.created_at + 48.hours && self.restaurants.count == 0
    UserMailer.theactionofthemail(self).deliver_later
 end

I tried it like this because i saw that with sidekiq i didn't have to create job to deliver_later my UserMailers .. :)

Any Clues ? If it's not clear tell me !

Thank you in Advance

Tiff images are not rendered when using PDFKit

I am using PDFKit to generate a PDF file with Tiff images

kit = PDFKit.new("<img src='test.tif'")
kit.to_file("hello.pdf")

But in the output PDF file, Tiff images are not rendered. I have tried a JPEG file. It's working perfectly. Any help would be appreciated.

mercredi 6 septembre 2017

How to modify the response of as_json in ruby on rails?

I have a model called Event, which in turn has_one association with EventType

event = Event.last

event.as_json(include: {event_type: {only: :name}}, only: :event_type)

This is giving me output

{ :event_type=> { "name"=>"Chat" } }

But my desired response is

{ :event_type => "Chat" }

How can I achieve this?

I would like to know how to show an error message in my rails project? Thanks :)

I would like to know how to show an error message in my rails project? but I do not know how to implement an error message for the user. I think I could put this solution inside the 'if'. Someone Can help me or there is other solution? Thanks :))

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :ldap_authenticatable,:rememberable, :trackable

  #validates :username, presence: true, uniqueness: true

  #before_validation :get_ldap_email
  validates_uniqueness_of :email, :allow_blank => true

  before_save :get_ldap_email


  def get_ldap_email

    ldapEmail =  Devise::LDAP::Adapter.get_ldap_param(self.username,"mail")
      self.email = Devise::LDAP::Adapter.get_ldap_param(self.username,"mail").first

     if Devise::LDAP::Adapter.get_ldap_param(self.username,"mail") == null

     end

     else

     end

  end
  # use ldap uid as primary key
  #before_validation :get_ldap_id
  #def get_ldap_id
   # self.id = Devise::LDAP::Adapter.get_ldap_param(self.username,"uidnumber").first
  #end

  # hack for remember_token
  #def authenticatable_token
  #  Digest::SHA1.hexdigest(email)[0,29]
  #end
  has_many :votes , :dependent => :delete_all
  has_many :ideas , :dependent => :delete_all
end

How convert 'link_to' to Absolute in Rails

I've a problem in my program, I add in DB a link, for example, "www.google.com" and when I clic in the link I'm redirected to localhost:3000/www.google.com, this doesn't happen when I put "http://www.google.com" in DB.

My code

<td><%= link_to t.title, t.link_to_idea, :target => "_blank" %></td>

How do I make to convert this link always in absolute? (I think I this's solution)

Thanks!!

Replace the Role_requirement plugin with a gem and fix the issue with class_inheritable_array

We Have a project working in Rails 3.1.16 and ruby 1.9.3. We are planning to upgrade the rails version to 3.2. The issue we have encountered is when we update the Gemfile with

gem 'rails', '3.2.6' 

and do the bundle install. and every thing works perfects . only the

DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://ift.tt/wl0LFP. (called from at /home/*****/********/config/environment.rb:6)

when we tries to do the localhost:3000 gets the below error,

Started GET "/" for 127.0.0.1 at 2017-09-06 11:59:02 +0530

ActionController::RoutingError - undefined method `class_inheritable_array' for ApplicationController:Class:

when i take the ApplicationController,

it contains a

require File.join(Rails.root, 'lib', 'role_requirement_system.rb')
  include RoleRequirementSystem

also when navigate to the RoleRequirementSystem file, it shows the

module RoleRequirementSystem
  def self.included(klass)
    klass.send :class_inheritable_array, :role_requirements
    klass.send :include, RoleSecurityInstanceMethods
    klass.send :extend, RoleSecurityClassMethods
    klass.send :helper_method, :url_options_authenticate? 

    klass.send :role_requirements=, []

  end

class_inheritable_array is the issue we think, the reason is there in active_support. when I tried in the rails 3.1.16, it shows some code definition in the active_support, and when I moved to the 3.2.6, there is no code definition.Is this my error when upgrading the Rails version?. TIA

mardi 5 septembre 2017

Join HTML string from Array on nested content_tag

I am building a block of HTML code using Rails content_tag helper and I do know how to generate nested blocks of HTML. The only challenge I face right now is how to join HTML string from an array with HTML elements generated by content_tag.

For example:

options = ["<li>Three</li>", "<li>Four</li>", "<li>Five</li>"]

// This is code to generate blocks of HTML
out = []
out << content_tag(:ul,  
   content_tag(:li, "One") + 
   content_tag(:li, "Two") + 
   options.join(''),
:class => ["class_1", "class_2"])
safe_join(out)

// Expect result should be like
<ul class="class_1 class_2">
   <li>One</li>
   <li>Two</li>
   <li>Three</li>
   <li>Four</li>
   <li>Five</li>
</ul>

// Actual result
<ul class="class_1 class_2">
   <li>One</li>
   <li>Two</li>
   "<li>Three</li><li>Four</li><li>Five</li>"
</ul>

However, if I use the html_safe approach like below, it will work.

%{<ul>
   <li>One</li>
   <li>Two</li>
   #{options.join('')}
 </ul>
}.html_safe

Any suggestions on what I should change?

I18n::ArgumentError in Admin/main#index

I am newbie to ruby devlopment. I got this error:

Showing /home/User/.gem/ruby/1.9.3/gems/admin-0.0.5/app/views/admin/main/index.html.haml where line #129 raised:


 Object must be a Date, DateTime or Time object. nil given.

Thanks in advance

Better method to find the second largest element in ruby on rails active record query

I am using this query to find the 2nd largest element. I am making query on value column.

Booking.where("value < ?", Booking.maximum(:value)).last

Is there any better query than this? Or any alternative to this

Devise after user login create action with table relationship

after User login with devise_token_auth then create operation_system name with "android" or "ios" so what should i do?

class CreateOperatingSystems < ActiveRecord::Migration[5.1]
  def change
    create_table :operating_systems do |t|
      t.string :name
      t.references :user, foreign_key: true

      t.timestamps
    end
  end
end

class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table(:users) do |t|
       .......................
    end
  end
end

How can I overwrite will_paginate page_entries_info method?

I have a problem with the display of the text messages from page_entries_info method. I want to change text in that.

Any Idea?

How to make Custom Association

class Order < ApplicationRecord
has_many :order_stages
has_many :stages , :through=> :order_stages
end
class Stage < ApplicationRecord
    has_many :order_stages
    has_many :orders , :through=> :order_stages
end
class OrderStage < ApplicationRecord
  belongs_to :order
  belongs_to :stage
end

these table has_many :through association . How to make the custom association to these table.

lundi 4 septembre 2017

Resque workers dying silently

I'm having issues with the workers that I have set up for a website. Here's Some background of the app: It runs on rails 3.0.2, using mongodb, redis gem 2.2.2. In order to keep the workers up and running I have set up the god gem and specify that 6 workers should run in the production environment. I'll be pasting the resque.god.rb file bellow. Also, there's a unique Ubuntu server that is set up for the resque-workers and elasticsearch services only so it doesn't share any other service.

My problem is that for any reason, the workers keep dying and just log "***Exiting..." in my log/resque-worker.log file which is extremely annoying because I don't know what is going on. It doesn't log anything in the syslog file nor the dmesg

This is a piece of what I get in the log (not helpful for me)

*** Starting worker workers:19166:*
*** Starting worker workers:19133:*
*** Running before_first_fork hook
*** Exiting...
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/rake-0.8.7/lib/rake/alt_system.rb:32: Use RbConfig instead of obsolete and deprecated Config.
(in /data/www/tap-production/releases/20170904162514)
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/activesupport-3.0.20/lib/active_support/dependencies.rb:242:in `block in require': iconv will be deprecated in the future, use String#encode instead.
*** Running before_first_fork hook
*** Exiting...
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/rake-0.8.7/lib/rake/alt_system.rb:32: Use RbConfig instead of obsolete and deprecated Config.
(in /data/www/tap-production/releases/20170904162514)
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/activesupport-3.0.20/lib/active_support/dependencies.rb:242:in `block in require': iconv will be deprecated in the future, use String#encode instead.
*** Starting worker workers:19251:*
*** Starting worker workers:19217:*
*** Running before_first_fork hook
*** Exiting...
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/rake-0.8.7/lib/rake/alt_system.rb:32: Use RbConfig instead of obsolete and deprecated Config.
(in /data/www/tap-production/releases/20170904162514)
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/activesupport-3.0.20/lib/active_support/dependencies.rb:242:in `block in require': iconv will be deprecated in the future, use String#encode instead.
*** Running before_first_fork hook
*** Exiting...
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/rake-0.8.7/lib/rake/alt_system.rb:32: Use RbConfig instead of obsolete and deprecated Config.
(in /data/www/tap-production/releases/20170904162514)
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/activesupport-3.0.20/lib/active_support/dependencies.rb:242:in `block in require': iconv will be deprecated in the future, use String#encode instead.
*** Starting worker workers:19330:*
*** Starting worker workers:19297:*
*** Running before_first_fork hook
*** Exiting...
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/rake-0.8.7/lib/rake/alt_system.rb:32: Use RbConfig instead of obsolete and deprecated Config.
(in /data/www/tap-production/releases/20170904162514)
/usr/local/www/tap-production/shared/bundle/ruby/1.9.1/gems/activesupport-3.0.20/lib/active_support/dependencies.rb:242:in `block in require': iconv will be deprecated in the future, use String#encode instead.

Here's my resque.god.rb code:

require 'tlsmail'
rails_env = ENV['RAILS_ENV']
rails_root = ENV['RAILS_ROOT']
rake_root = ENV['RAKE_ROOT']
num_workers = rails_env == 'production' ? 6 : 1
# Change cache to my_killer_worker_job if you are testing in development. remember to enable it on config/resque_schedule.yml - Fabian
queue = rails_env == 'production' ? '*' : 'my_killer_worker_job'

God::Contacts::Email.defaults do |d|
  Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
  if rails_env == "production"
    #Change this settings for your own purposes
    d.from_name = "#{rails_env.upcase}: Process monitoring"
    d.delivery_method = :smtp
    d.server_host = 'smtp.gmail.com'
    d.server_port = 587
    d.server_auth = :login
    d.server_domain = 'gmail.com'
    d.server_user = 'XXXX@gmail.com'
    d.server_password = 'XXXX'
  end
end



God.contact(:email) do |c|
  c.name = 'engineering'
  c.group = 'developers'
  c.to_email = 'engineering@something.com'
end

num_workers.times do |num|
  God.watch do |w|
    w.name          = "resque-#{num}"
    w.group         = 'resque'
    w.interval      = 30.seconds
    w.env           = { 'RAILS_ENV' => rails_env, 'QUEUE' => queue, 'VERBOSE' => '1' }
    w.dir           = rails_root
    w.start         = "bundle exec #{rake_root}/rake resque:work"
    w.start_grace   = 10.seconds
    w.log           = File.join(rails_root, 'log', 'resque-worker.log')

    # restart if memory gets too high
    w.transition(:up, :restart) do |on|
      on.condition(:memory_usage) do |c|
        c.above = 200.megabytes
        c.times = 2
        # c.notify = 'engineering'
      end
    end

    # determine the state on startup
    w.transition(:init, { true => :up, false => :start }) do |on|
      on.condition(:process_running) do |c|
        c.running = true
        # c.notify = 'engineering'
      end
    end

    # determine when process has finished starting
    w.transition([:start, :restart], :up) do |on|
      on.condition(:process_running) do |c|
        c.running = true
        c.interval = 5.seconds
        # c.notify = 'engineering'
      end

      # failsafe
      on.condition(:tries) do |c|
        c.times = 5
        c.transition = :start
        c.interval = 5.seconds
        # c.notify = 'engineering'
      end
    end

    # start if process is not running
    w.transition(:up, :start) do |on|
      on.condition(:process_running) do |c|
        c.running = false
        c.notify = {:contacts => ['engineering'], :priority => 1, :category => "workers"}
      end
    end


  end
end

Please let me know your thoughts.

Rails customize json generating using eagerloading rails

I have a model User and another Images and relationship in between both of these as:

User has_many :images

Image belongs_to :user

Now I'm writing a json api to get user with his images using eagerloading like,

User.all.as_json({:include=> {:images => {only: [:image_url] } })

Now I want to get images and want to override JSON at the time of generating like we can override as_json method in my user model same as I want to override at time time of include, but that is not generating using as_json in Image Model.

samedi 2 septembre 2017

Is there a shorthand equivalent for the double pipe operator which treats empty strings as falsy?

In Ruby, it's common to use the double pipe operator to test if a variable is falsy and to apply some kind of default setting when variables are undefined. Here's a line of config I just came across in a codebase I'm doing some work on:

config.uh_product_name = ENV['UH_PRODUCT_NAME'] || 'Unicorn Hunt'

This is all well and good if ENV["UH_PRODUCT_NAME"] is nil. But in this case, because of the way the .env file is set by default, ENV["UH_PRODUCT_NAME"] is an empty string "", which is truthy. So the default is not applied.

I could do this to handle this case:

config.uh_product_name = ENV['UH_PRODUCT_NAME'].present? ? 'Unicorn Hunt' : ENV['UH_PRODUCT_NAME'] 

But that's much less readable and ends up with a line of code that potentially stretches off screen.

So, does anyone know of a shorthand operator along the lines of || that applies Rails's .blank? or treats empty strings as falsy? Something like this perhaps:

config.uh_product_name = ENV['UH_PRODUCT_NAME'] ?|| 'Unicorn Hunt'