dimanche 30 décembre 2018

ruby hash get from dynamic key and value (MIB SNMP)

Im a newbie on ruby, i have hash data like below.

person = {"PoolName.11.22.33":"pool_a","PoolMemberName.11.22.33.11":"member_pool_a1","PoolMemberScore.11.22.33.11":0,"PoolName.11.22.44":"pool_b","PoolMemberName.11.22.44.11":"member_pool_b1","PoolMemberName.11.22.44.12":"member_pool_b2","PoolMemberScore.11.22.44.11":2,"PoolMemberScore.11.22.44.12":3,"PoolName.11.22.55":"pool_c","PoolMemberName.11.22.55.11":"member_pool_c1","PolMemberName.11.22.55.12":"member_pool_c2","PoolMemberName.11.22.55.13":"member_pool_c3","PoolMemberScore.11.22.55.11":11,"PoolMemberScore.11.22.55.12":22,"PoolMemberScore.11.22.55.13":33}

Results i should get like following below:

"pool_a.member_pool_a1" : 0,
"pool_b.member_pool_b1" : 2,
"pool_b.member_pool_b2" : 3,
"pool_c.member_pool_c1" : 11,
"pool_c.member_pool_c2" : 22,
"pool_c.member_pool_c3" : 33

I have code like following below :

begin
        person.each{|key|
            if ( key =~ /PoolName/ || key =~ /PoolMemberName/ )
                newid = key.gsub(/PoolName./, "").gsub(/PoolMemberName./, "")
                val = event.get(key).gsub(/\/Common\//, "").gsub(/\./, "_")
                event.set(newid, val)
                event.remove(key)
            end
        }

    rescue Exception => e
        event.set("logstash_ruby_exception", "underscores: " + e.message)
    end

samedi 29 décembre 2018

what will happen if i store collection of data into the instance variable under initialize method?

what will happen if i store collection of data into instance variable under initialize method?

when i create the object of the class, instance variable are there in the object with lots of data. I want to understand how it slow down the execution.

Any help would be appreciated.

vendredi 28 décembre 2018

How I can use database view with rails mysql? [on hold]

I want to use database view in rails and i'm using mysql.Please any body can help thanks in advance.

Rails: How to access session parameter / ActiveRecord::StatementInvalid in Orders#create

I am working on a multistep form for an order placement section which uses a session session[:order_params] to store all form inputs before submit.

I need to be able to access a particular parameter (land) from the session in order to query for another resource (shippingservice) when navigating back in the form.

In my orders_controller.rb I have:

@shippingservices = @cart.available_shipping_services.joins(:lands).where(:lands => {:id => params[:id]})

but would need to specify the land.id from the session[:order_params].

When using session[:order_params] I get ActiveRecord::StatementInvalid in Orders#create:

Mysql::Error: Unknown column 'id.ship_to_last_name' in 'where clause': SELECT `shippingservices`.* FROM `shippingservices` 
INNER JOIN `zones` ON `zones`.`id` = `shippingservices`.`zone_id` 
INNER JOIN `lands_zones` ON `lands_zones`.`zone_id` = `zones`.`id` 
INNER JOIN `lands` ON `lands`.`id` = `lands_zones`.`land_id` 
WHERE `id`.`ship_to_last_name` = 'Smith' 
AND `id`.`ship_to_address` = 'Somewherestreet' 
AND `id`.`ship_to_city` = 'Nowheretown' 
AND `id`.`ship_to_postal_code` = '99999' 
AND `id`.`phone_number` = 'some number' 
AND `id`.`shippingservice_id` = '34' 
AND `id`.`email` = 'someone@example.tld' 
AND `id`.`land_id` = '85' 
AND `id`.`ship_to_first_name` = 'John' 
AND (weightmin <= 200 AND weightmax >= 200 AND heightmin <= 12 AND heightmax >= 12 AND shippingservices.shippingcarrier = '1') AND (lengthmax >= 210 AND widthmax >= 149)

Since the correct land_id is present I am wondering how to provide only that value to the query.

Thank you in advance!

How to stop a nohup process running rails server on port 3000

I have started a rails server puma by using the following command.

 nohup rails server &

its output was [2] 22481 along with the following:

nohup: ignoring input and appending output to 'nohup.out'

But now I have forget the returned process id, so how can I detect the process id so as to delete the process on aws.

jeudi 27 décembre 2018

Rails: dynamic select on multistep form not keeping selected

I am working on a multistep form for an order placement process following Ryan Bates's Multistep Tutorial #217 which uses a session. On the first step I have two select fields: one for countries (land) and a dynamic one for shipping services. After a land has been selected the shipping services are loaded into the second select field through javascript/jQuery and the total price is calculated again through JS.

app/views/orders/_shipping_step.html.erb

<%= f.collection_select(:land_id, Land.all, :id, :name, {:prompt => "select a country"}, {:id => 'lands_select'}) %>
<%= f.select(:shippingservice_id, options_for_select(@shippingservices.collect { |s| [s.name.titleize, s.id, {'data-price' => s.price}] }, :selected => f.object.shippingservice_id), {:prompt => "select a carrier"}, {:id => "shippingservices_select"}) %>

ajax script

$(document).on("change", "#lands_select", function(event){
  $.ajax({
    url: "/carts/update_shipping/" + event.target.value,
    type: "GET",
  })
});

On the shipping details step of the multistep form I can choose a land, the corresponding options for shipment are loaded and I can choose one. When progressing to the payment step, I can place the order and everything works, but in case I want to return from the payment step to the order step to change something, the shipping services selector displays options for land_id = 1, while the land select displays the choose country, for example id 84.

I added :selected => session[:cart_params]) to the shipping service select, but it does not appear to be working. :selected => f.object.shippingservice_id keeps priority or standard shipping options, but for Land_id 1.

How can I get this working? Is it the select field or the JS? Why doesn't the second select keep the chosen land in memory?

Thank you in advance!

LOG:

Started GET "/orders/new" for 127.0.0.1 at Thu Dec 27 22:08:52 +0100 2018
Processing by OrdersController#new as HTML
  Cart Load (0.3ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 1]]
  Land Load (1.4ms)  SELECT `lands`.* FROM `lands` 
  CartItem Load (0.3ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.2ms)  SELECT MAX(`cart_items`.`length`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.2ms)  SELECT MAX(`cart_items`.`width`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
  CACHE (0.0ms)  SELECT `lands`.* FROM `lands` 
  Shippingservice Load (0.6ms)  SELECT `shippingservices`.* FROM `shippingservices` INNER JOIN `zones` ON `zones`.`id` = `shippingservices`.`zone_id` INNER JOIN `lands_zones` ON `lands_zones`.`zone_id` = `zones`.`id` INNER JOIN `lands` ON `lands`.`id` = `lands_zones`.`land_id` WHERE `lands`.`id` = 1 AND (weightmin <= 50 AND weightmax >= 50 AND heightmin <= 3 AND heightmax >= 3 AND shippingservices.shippingcarrier = ‘1’) AND (lengthmax >= 210 AND widthmax >= 149)
  Product Load (0.3ms)  SELECT `products`.* FROM `products` WHERE `products`.`id` = 3 LIMIT 1
  Hero Load (0.2ms)  SELECT `heros`.* FROM `heros` WHERE `heros`.`id` = 18 LIMIT 1
  Rendered orders/_shipping_step.html.erb (13.7ms)
  Rendered orders/new.html.erb within layouts/application (16.2ms)
  Rendered layouts/_header.html.erb (0.1ms)
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 44ms (Views: 23.0ms | ActiveRecord: 3.9ms)

Progressing to the payment step:

Started POST "/orders" for 127.0.0.1 at Thu Dec 27 22:09:33 +0100 2018
Processing by OrdersController#create as HTML
  Parameters: {"order"=>{"ship_to_last_name"=>”surname”, "ship_to_address"=>”street”, "ship_to_city"=>”city”, "ship_to_postal_code"=>”postcode”, "phone_number"=>”somenumber”, "shippingservice_id"=>"27", "email"=>”something@example.tld”, "land_id"=>"85", "ship_to_first_name"=>”firstname”}, "authenticity_token"=>”somestring”, "utf8"=>"✓", "commit"=>"Continue"}
  Cart Load (0.2ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 1]]
  Land Load (1.5ms)  SELECT `lands`.* FROM `lands` 
  CartItem Load (0.4ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.2ms)  SELECT MAX(`cart_items`.`length`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.2ms)  SELECT MAX(`cart_items`.`width`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
  Land Load (0.4ms)  SELECT `lands`.* FROM `lands` WHERE `lands`.`id` = 85 LIMIT 1
  Shippingservice Load (0.3ms)  SELECT `shippingservices`.* FROM `shippingservices` WHERE `shippingservices`.`id` = 27 LIMIT 1
  Product Load (0.3ms)  SELECT `products`.* FROM `products` WHERE `products`.`id` = 3 LIMIT 1
  Hero Load (0.3ms)  SELECT `heros`.* FROM `heros` WHERE `heros`.`id` = 18 LIMIT 1
  Rendered orders/_payment_step.html.erb (7.0ms)
  Rendered orders/new.html.erb within layouts/application (8.9ms)
  Rendered layouts/_header.html.erb (0.1ms)
  Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 39ms (Views: 13.7ms | ActiveRecord: 4.6ms)

Selecting the shipping country:

Started GET "/carts/update_shipping/85" for 127.0.0.1 at Thu Dec 27 22:09:27 +0100 2018
Processing by CartsController#update_shipping as */*
  Parameters: {"id"=>"85"}
  Cart Load (0.2ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 1]]
  Land Load (66.9ms)  SELECT `lands`.* FROM `lands` 
  CartItem Load (0.4ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.2ms)  SELECT MAX(`cart_items`.`length`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.2ms)  SELECT MAX(`cart_items`.`width`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
  Shippingservice Load (0.6ms)  SELECT `shippingservices`.* FROM `shippingservices` INNER JOIN `zones` ON `zones`.`id` = `shippingservices`.`zone_id` INNER JOIN `lands_zones` ON `lands_zones`.`zone_id` = `zones`.`id` INNER JOIN `lands` ON `lands`.`id` = `lands_zones`.`land_id` WHERE `lands`.`id` = 85 AND (weightmin <= 50 AND weightmax >= 50 AND heightmin <= 3 AND heightmax >= 3 AND shippingservices.shippingcarrier = ‘1’) AND (lengthmax >= 210 AND widthmax >= 149)
  Rendered carts/_shippingservice.html.erb (0.2ms)
  Rendered carts/update_shipping.js.erb (2.9ms)
Completed 200 OK in 87ms (Views: 7.8ms | ActiveRecord: 68.6ms)

Returning to the shipping details step:

Started POST "/orders" for 127.0.0.1 at Thu Dec 27 22:09:35 +0100 2018
Processing by OrdersController#create as HTML
  Parameters: {"authenticity_token"=>”somestring”, "utf8"=>"✓", "back_button"=>"Back"}
  Cart Load (0.3ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 1]]
  Land Load (2.4ms)  SELECT `lands`.* FROM `lands` 
  CartItem Load (0.5ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.3ms)  SELECT MAX(`cart_items`.`length`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
   (0.4ms)  SELECT MAX(`cart_items`.`width`) AS max_id FROM `cart_items` WHERE `cart_items`.`cart_id` = 1
  CACHE (0.0ms)  SELECT `lands`.* FROM `lands` 
  Shippingservice Load (0.7ms)  SELECT `shippingservices`.* FROM `shippingservices` INNER JOIN `zones` ON `zones`.`id` = `shippingservices`.`zone_id` INNER JOIN `lands_zones` ON `lands_zones`.`zone_id` = `zones`.`id` INNER JOIN `lands` ON `lands`.`id` = `lands_zones`.`land_id` WHERE `lands`.`id` = 1 AND (weightmin <= 50 AND weightmax >= 50 AND heightmin <= 3 AND heightmax >= 3 AND shippingservices.shippingcarrier = ‘1’) AND (lengthmax >= 210 AND widthmax >= 149)
  Product Load (0.3ms)  SELECT `products`.* FROM `products` WHERE `products`.`id` = 3 LIMIT 1
  Hero Load (0.2ms)  SELECT `heros`.* FROM `heros` WHERE `heros`.`id` = 18 LIMIT 1
  Rendered orders/_shipping_step.html.erb (16.5ms)
  Rendered orders/new.html.erb within layouts/application (18.4ms)
  Rendered layouts/_header.html.erb (0.2ms)
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 109ms (Views: 24.0ms | ActiveRecord: 5.1ms)

Verify if user is approved by admin before login

Hello I followed this tutorial https://github.com/plataformatec/devise/wiki/How-To:-Require-admin-to-activate-account-before-sign_in to verify that the user is approved by the admin before he can connect.

I would like to add the condition to test that it is approved to connect

here is my controller session_controller.rb

class SessionsController < Devise::SessionsController
before_action :set_email

 def new
  super
 end

def create
 self.resource = warden.authenticate!(auth_options)
 set_flash_message(:notice, :signed_in) if is_navigational_format?
 sign_in(resource_name, resource)

 if !session[:return_to].blank?
  redirect_to session[:return_to]
  session[:return_to] = nil

 else
  respond_with resource, :location => after_sign_in_path_for(resource)
end

end

def confirm_email
 user = User.find_by_confirm_token(params[:id])
 if user
  user.email_activate
  flash[:success] = "Welcome to the Sample App! Your email has been 
confirmed.
  Please sign in to continue."
  redirect_to signin_url
 else
  flash[:error] = "Sorry. User does not exist"
  redirect_to root_url
end
end


def set_email
 @email = params[:email];
 @user1 = params[:user];
end



end

Thanks

List all associated model records present in another model present in another namespace in rails

I have two models like:

class Superadmin::Company < ApplicationRecord
  belongs_to :user
  has_many :garments
end

2nd

class Garment < ApplicationRecord
   has_many :garments ,:class_name => "Superadmin::Company", dependent: :destroy
end

But when I search like

company = Superadmin::Company.find(9)
company.garments

Its give error: as

 Garment Load (1.3ms)  SELECT `garments`.* FROM `garments` WHERE `garments`.`company_id` = 9 ORDER BY created_at asc
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'garments.company_id' in 'where clause': SELECT `garments`.* FROM `garments` WHERE `garments`.`company_id` = 9 ORDER BY created_at asc
    from /home/tukatech/rails_projects/live_tukagarments/.bundle/gems/activerecord-5.0.7.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:218:in `query'

Table names in database is as:

1. garments
2. superadmin_companies

please provide if there is a correct way to search using rails foreign key associations relation.

mercredi 26 décembre 2018

Rails 3: Redirecting only specific users to new application while others should be able to access old application

My employer got new website and wants me to redirect old website(in Rails 3) users to new website whenever customers try to access old website . Tricky part is that they want their internal staff to continue to access old website with same URL. But when outside customer comes on old website, they want to redirect him/her to new website.

Is this possible?

What I can think of adding “staff” keyword at end of URL, if incoming URL in application controller has “staff” keyword then I can allow internal staff to access old website. If incoming URL does not have “staff” keyword in URL, then i can redirect to new website.

Does this make sense?

Add a model in the present in the other namespace as foreign key

In Rails I want to include a model_id as foreign key into another model which is present in another namespcae. I have two models as
First:

class Garment < ApplicationRecord
end

Second:

class Superadmin::Company < ApplicationRecord
end

I am using the following command for it.

 rails g migration addCompanyIdToGarment company:references

which give output like:

class AddCompanyIdToGarment < ActiveRecord::Migration[5.0]
  def change
    add_foreign_key :garments, :company
  end
end

which is incorrect, please provide the correct command or procedure to do it.

Delete a model present in another namespace rails

In Rails when I have made one Model as the foreign key in another model then I can delete that model while speciying its relation like:

class User < ApplicationRecord
  has_many :garments, dependent: :destroy  
end

But if I have one model which is created in another namespace like superadmin them how to write the dependent destroy relation in that case for example I am using :

class User < ApplicationRecord
  has_one superadmin::company , dependent: :destroy
end 

which is incorrect.
The model company is present in namespace superadmin, please tell if their is a correct a way possible. Thanks in advance

PDF prawn not rendering into Chinese

I have an issue where my Chinese text is not getting rendered in PDF document. Can anyone help me out with this.Thanks in advance

pdf.font_families.update("Neue Haas Grotesk Disp Reg" => {
:normal =>"#{Rails.root.join('vendor/assets/fonts/custom_font/gkai00mp.ttf')}"
})

How to fix a 'SystemStackError: stack level too deep' error with a large amount of ActiveRecord conditions

I have an ActiveRecord query which iteratively adds or conditions to a search:

places.each do |place|
  people = people.or(People.within_radius_of(place.latitude, place.longitude, place.radius).select(:id))
end

within_radius_of is a custom Postgresql query to find people within a radius.

This works without issue with our original max target of 100 places, but 600 places were added to a search and I get the stack level too deep issue.

What are the implications of increasing the stack size? Default is 1MB, for example what issues might occur if I set it to 8MB or more?

Can this query be rewritten to avoid the error?

Rails: query for 2-step relation through join-table + has many relation

I am working on improving my database scheme. Currently I use a has_many through structure with a land model/table a shippingservice model/table and a postzone model/table, which connects land and shipping tables.

Has many through

I can query this way:

@shippingservices = @cart.available_shipping_services.includes(:lands, :postzones).where('postzones.land_id = ?', params[:id])

And get all shipping services for a given land (country).

But this way I end up with a lot of repetition in the postzone table and maintenance is quite difficult. It would be much easier if I could collect lands in zones with many lands and than connect shipping services to a zone. Just like in this scheme:

Join table + has many

How would I query in this case for all shipping services for a given land?

For a join table I would do something like:

@shippingservices = @cart.available_shipping_services.joins(:lands => :zones).where('lands_zones_join.land_id = ?', params[:id])

Which does not work, since I get:

Mysql::Error: Unknown column 'lands_zones_join.zone_id' in 'where clause': SELECT `shippingservices`.* FROM `shippingservices` 
INNER JOIN `zones` ON `zones`.`id` = `shippingservices`.`zone_id` 
INNER JOIN `lands_zones` ON `lands_zones`.`zone_id` = `zones`.`id` 
INNER JOIN `lands` ON `lands`.`id` = `lands_zones`.`land_id` 
INNER JOIN `lands_zones` `zones_lands_join` ON `zones_lands_join`.`land_id` = `lands`.`id` 
INNER JOIN `zones` `zones_lands` ON `zones_lands`.`id` = `zones_lands_join`.`zone_id` 
WHERE (weightmin <= 50 AND weightmax >= 50 AND height >= 3 AND shippingservices.shippingcarrier = '1') AND (length >= 210 AND width >= 149) AND (lands_zones_join.zone_id = '2')

Is this even possible? How can I get this to work?

Thank you in advance!

mardi 25 décembre 2018

Active records/SQL: find options at data point closest to limit

I am working on a shipping cost routine. I have a cart, cart_items and shippingservice model. I know length, width, height and weight of all cart_items and calculated the accumulated weight + height and found the max length + width for the shipment.

I have in my cart model a method which already takes weight, height and carrier into account

# Methods shippingservices
def available_shipping_services
  Shippingservice.where('weightmin <= ? and weightmax >= ?', total_weight, total_weight).where('height >= ?', total_height).where('length >= ?', max_length).where('width >= ?', max_width).where('shippingservices.shippingcarrier = ?', '1') 
end

The problem I have is that the shipping carrier has standard and express shipments for different sizes (compact and large).

International compact M 381mm length, 305mm width, 20mm height, 51-100gr

International large S 450mm length, 450mm width, 240mm height, 1-350gr

Int. Priority compact M 381mm length, 305mm width, 20mm height, 51-100gr

Int. Priority large S 450mm length, 450mm width, 240mm height, 1-350gr

There are a few cases where both compact and large options overlap and are displayed together and I end up with 4 options where the closest option in size as standard and priority would be enough.

For the 4 examples above I would get 4 options when the cart would weigh below 100gr, have height below 20mm and be smaller than 381x305mm.

I would like to find an active records or sql query, which would exclude the superfluous options and only displayed the closest ones.

Something like: take all shippingservice entries which respect weight and height, for the integer value point closest to cart width/length.

How can I achieve this?

Thank you very much in advance!

lundi 24 décembre 2018

Convert id into string to use in url

I want to convert id into string to use in url

@tutorial_id = Demotutorial.where("job_id = ?", @job_id).select( "id")
@t_id = @tutorial_id.to_s
   render json: @t_id

Getting this error

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Tutorial Json array

{"demotutorials":[{"demotutorials":{"id":50}}]}

How paperclip retruns the path to that file which is uploaded rather then path with file name

Hi I am using Ruby on rails to load the assets on to the page with paperclip:

In paperclip by using

render file: @garment.xhtml_file.url

will return the path

:"/home/tukatech/rails_projects/live_tukagarments/public/system/xhtml_files/60/Cycle_Suit.xhtml?1545631909"

But my requirement is upto :

"/home/tukatech/rails_projects/live_tukagarments/public/system/xhtml_files/60/Cycle_Suit.xhtml"

not including the dust is there a way to do it in paperclip

Rails server do not load assets present locally to xhtml file rather then requesting the server to load them

Hi my code is like inside x3dom xhtml :

<ImageTexture containerField='diffuseTexture' src='Colorways_xhtml/Light_violet_Back_Colorways.jpg'></ImageTexture> 

when ImageTexture load images It ask the server by making request as:

Loading: /garments/Colorways_xhtml/Light_violet_Back_Colorways.jpg

Is there a way that it should search the file with the current directory like ./Colorways_xhtml/Light_violet_Back_Colorways.jpg instead requesting server for the file

vendredi 21 décembre 2018

Path for nested resources

I have a nested resources but i am not get a path for these resources.

routes.rb

namespace :admin do
   resources :demos do
      resources :demojobs, :path => "jobs" do
        resources :demotutorials 
      end  
    end
end

I have try to get the new page of demotutorials page using following link:

new_admin_demo_demojob_demotutorials_path

but getting error

No route matches {:action=>"new", :controller=>"admin/demotutorials"}

working with rails version : 3.2.11

Rails select form: displaying and using select form value before submit?

I am working on a multi step form for an order placement process. In it I have two selectors for shipping countries and shipping services. After selecting the country all shipping services are displayed for a given place and weight. When the order is placed everything is written to the model. All the shipping details process is done through a multistep form following Ryan Bates #217 Multistep Forms

The shipping service selector is populated through a javascript ajax call after the shipping country has been chosen. I followed this two tutorials Dynamic select boxes with Rails 4 and Dependent country city state.

$(document).on("change", "#lands_select", function(event){
  $.ajax({
    url: "/carts/update_shipping/" + event.target.value,
    type: "GET"
  })
});

update_shipping.js.erb

$("#shippingservices_select").empty()
  .append("<%= escape_javascript(render(:partial => @shippingservices)) %>");

_shippingservice.html.erb

<option value="<%= shippingservice.id %>"><%= shippingservice.name.titleize %></option>

In addition to this I would like to display the shipping cost related to the selection made in both selectors below the form together with the calculated total shipping cost.

How can I do this? Since both values have not been written to the order database yet I would have to display the resulting price of the second selector selection which is inside the shipping services table, but since the order has bot been written yet I cannot call it through the order instance variable. My guess is that I would have to do this adapting the ajax call, could that be? How would I have to do this?

What I have now is that the form is populated through json produced by the order controller's update_shipping action as far as I understand.

Thanks in advance!

How to clear garbage collection in ruby?

How to clear garbage collection in ruby? I configured my rails app in AWS. I have used nginx and puma manager.

jeudi 20 décembre 2018

Rails can't verify CSRF token authenticity after long idle

I have a Rails app and I'm using devise with timeoutable. If the user's computer is left idle for some time (about an hour I think), I get the following server logs:

Processing by Api::SessionsController#create as JSON
Parameters: {"email"=>"xxx@xxx.xxx", "password"=>"[FILTERED]"}
WARNING: Can't verify CSRF token authenticity
...
Completed 200 OK in 553ms (Views: 462.6ms | Solr: 0.0ms)
Started GET "/api/home" for ::ffff:150.129.131.50 at 2018-12-20 12:18:51 +0000
Processing by Api::HomeController#show as JSON
Completed 401 Unauthorized in 1ms

The CSRF token is normally working fine, the issue only occurs after an hour or so. This has the effect of logging the user out as soon as they log in. Here is the relevant code:

application_controller.rb

    protect_from_forgery
    before_filter :authenticate_user!

application.html.erb

    <%= csrf_meta_tags %>

application.js

    //= require jquery
    //= require jquery_ujs

sessions_controller.rb

    skip_before_filter :authenticate_user!

I am using the devise gem with timeoutable. This is also a single page app that uses Ajax requests to access an API, and the session cookie for user sessions. But I don't actually see how that's relevant anyway, since any web page would need to be able to handle an expired CSRF token somehow, and for whatever reason I'm not finding the solution.

It's also probably worth mentioning that changing the timeout_in to be very short, like 30 seconds, doesn't reproduce this error, and neither does changing the computer's sleep timer to 1 minute. Which makes sense given that it's the CSRF token that's expiring, not the user session.

Ruby v1.9.3

Rails v3.2.8

Devise v3.2.4

Unicorn v4.8.2

mercredi 19 décembre 2018

Rails where LIKE pass dynamic attribute with there values

I have search query and there I need to pass dynamic search attribute and values. Following query I am passing all field but those are not dynamic means Some time only first_name will be in search or some time first_name and last_name or some time first_name with age.

How the best way to pass those attributes and values as per found in search method.

Product.where('first_name like ? OR last_name like ? OR age BETWEEN ? AND ?', params[:first_nm], params[:last_nm], params[:age_start], params[:age_end])

Rspec 3.8, request spec, unable to set route with id

In the request spec for the show method i want to test the route cars/:id. If i write the path like the following i get a redirect to my root exception.

 describe '#show' do
  let(:car) {create :car}

it 'renders a partial' do
  get car_url(car.id)
  #get car_url, car.id
  expect(response).to render_template(:template)
end 

=> expecting <"template"> but was a redirect to <http://admin.example.com/>

When i change get car_url,car.id with get cars to test the #index method everything works fine. But i do not see myself able to add a id parameter to the route.

In the console the app object gives me:

irb(main):001:0> app.car_url(2)                                                                                                                                                     
=> "http://www.example.com/cars/2"

so the route is there. The factory is also a valid object saved to the database.

mardi 18 décembre 2018

Javascript: null is not an object (evaluating 'document.id(options.update).empty')

I have some javascript framework collisions.

I usually used the following function in Rails Apps:

// ArticleRequest funtion
function ArticleRequest (article_url, article_target) {
    var req = new Request.HTML({
        method: 'get',
        url: article_url,
        update: $(article_target),
    });
    req.send();
    };

This required MooTools-Core-1.2.1 and MooTools-More but I could do this:

<a onClick="ArticleRequest('/cases/show/<%= work.id %>', 'work<%= work.id %>');">

I had the function once and would define url and target options each time.

Unfortunately the use of both frameworks produce:

TypeError: undefined is not a function (near '...$(document).on...')

for a jQuery part related to an AJAX call, which I need for a newer app:

// Load selector on change
$(document).on("change", "#lands_select", function(event){
  $.ajax({
    url: "/carts/update_shipping/" + event.target.value,
    type: "GET"
  })
});

When I try to use a newer version of MooTools such as 1.6.0 the dynamic select works but the article request produces:

TypeError: null is not an object (evaluating 'document.id(options.update).empty')

- success - MooTools-Core-1.6.0.js:6026
- (anonymous function) - MooTools-Core-1.6.0.js:1106
- onStateChenge - MooTools-Core-1.6.0.js:5768
- (anonymous function) - MooTools-Core-1.6.0.js:1106
- (anonymous function)

Is there a way to have both functions working? Maybe by having them in vanilla Javascript?

Thanks in advance!

Coffee error undefined is not a function (near '...$(document).on...')

I am trying to implement a dynamic form in a Rails App through AJAX and did a couple of tutorials, but without success.

The Coffee part from my asset folder

$ ->
  $(document).on 'change', '#lands_select', (evt) ->
    $.ajax 'update_shipping',
      type: 'GET'
      dataType: 'script'
      data: {
        land_id: $("#lands_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic lands select OK!")

For this form in a view:

<%= form_for :cart, :url => {:action => "show_shipping"}, :html => {:method => "get"} do |f| %>
  <%= f.select(:land_id, options_for_select(@lands.collect { |l| [l.name.titleize, l.id] }, 0), {}, {:id => 'lands_select', :prompt => "select a country"}) %>
  <%= f.select(:shippingservice_id, options_for_select(@shippingservices.collect { |s| [s.title.titleize, s.id] }, 0), {}, {:id => 'shippingservices_select', :prompt => "select a carrier"}) %>
  <%= f.submit "Calculate shipping" %>
<% end %>

Which gets rendered as:

<form accept-charset="UTF-8" action="/carts/show_shipping/4" method="get">
  <div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div>
  <select id="lands_select" name="cart[land_id]" prompt="select a country"><option value="1">Afghanistan</option>
  ...
  <select id="shippingservices_select" name="cart[shippingservice_id]" prompt="select a carrier"><option value="7">Standard</option>
  ...
  <input name="commit" type="submit" value="Calculate shipping" />
</form>

produces an

TypeError: undefined is not a function (near '...$(document).on...')         

I have jQuery in my Javascript directory.

Why does this happen and how can I solve this?

lundi 17 décembre 2018

Rails: javascript addEventListener does not find element in dynamic form

I am trying to implement a dynamic form in a Rails App through AJAX and did a couple of tutorials, but without success.

The Javascript part from my application js file in the asset folder

var land = document.getElementById("cart_land_id");
land.addEventListener("change", function(){
  Rails.ajax({
    url: "/carts?land=" + land.value,
    type: "GET"
  })
})

For this form in a view:

<%= form_for @cart, :url => {:action => "show_shipping"}, :html => {:method => "get"} do |f| %>
  <%= f.select :land_id, options_for_select(@lands.map { |l| [l.name.titleize, l.id] }, {:id => 'lands_select', :prompt => "select a country"}) %><br>
  <%= f.select :shippingservice_id, options_for_select([]) %><br>
  <%= f.submit "Calculate shipping" %>
<% end %>

Which gets rendered as:

<form accept-charset="UTF-8" action="/carts/show_shipping/4" class="edit_cart" id="edit_cart_4" method="get">
  <div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div>
  <select id="cart_land_id" name="cart[land_id]"><option value="1">Afghanistan</option>
  ...
  <select id="cart_shippingservice_id" name="cart[shippingservice_id]"></select><br>
  <input name="commit" type="submit" value="Calculate shipping" />
</form>

produces an

TypeError: null is not an object (evaluating 'land.addEventListener')         

I have jQuery in my Javascript directory.

Why does this happen and how can I solve this?

How: 'on change' change selector through AJAX correctly?

I would like to implement an on change event to two select fields.

I have one select field for countries, a second select field for shipping options for a given country and when 1st country and 2nd shipping has been selected I would like to display the shipping cost.

I am following a tutorial about Dynamic select boxes with Rails 4 which is well written, but it does not work.

I have a carts_controller in apps/controller

class CartsController < ApplicationController
  def show
    @cart = Cart.find(params[:id])
    @lands = Land.find(:all)
    @shippingservices = @cart.available_shipping_services.includes(:lands, :postzones).where('postzones.land_id = ?', Land.first.id)
  end

  def show_shipping
    @shippingservice = Shippingservice.find_by("id = ?", params[:cart][:shippingservice_id])
  end

  def update_shipping
    @shippingservices = Shippingservice.where("land_id = ?", params[:land_id])
    respond_to do |format|
      format.js
    end
  end
end

routes.rb

  match '/carts/show_shipping/:id',  :to => 'carts#show_shipping', :as => :show_shipping
  match '/carts/update_shipping',    :to => 'carts#update_shipping'

In the tutorial there is a coffee script part. Unfortunately I do not know coffee. I adapted it, but might have made a mistake. It is in the asset javascript directory.

$ ->
  $(document).on 'change', '#lands_select', (evt) ->
    $.ajax 'update_shipping',
      type: 'GET'
      dataType: 'script'
      data: {
        country_id: $("#lands_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic lands select OK!")

app/views/carts/show.html.erb

<div id="cart_shipping">
  <%= form_for :cart, :url => {:action => "show_shipping"}, :html => {:method => "get"} do |f| %>
    <%= f.select(:land_id, options_for_select(@lands.collect { |l| [l.name.titleize, l.id] }, 0), {}, {:id => 'lands_select', :prompt => "select a country"}) %><br>
    <%= f.select(:shippingservice_id, options_for_select(@shippingservices.collect { |s|
            [s.title.titleize, s.id] }, 0), {}, {:id => 'shippingservices_select', :prompt => "select a carrier"}) %><br>
    <%= f.submit "Calculate shipping" %>
  <% end %>
</div>

app/views/carts/update_shipping.js.erb

$("#shippingservices_select").empty()
  .append("<%= escape_javascript(render(:partial => @shippingservices)) %>")

app/views/carts/_shippingservice.html.erb

<option value="<%= shippingservice.id %>"><%= shippingservice.name.titleize %></option>

When I load the page I get:

TypeError: undefined is not a function (near '...$(document).on...')

Did I miss something?

How can I get this done? Maybe even in plain javascript, since I know a little bit about Javascript ...

Thanks in advance!

Some more context: I have jQuery 2.2.4 and 2.2.4.min in asset folder and I have to use Rails 3.

Rails: active-records query for entry in range & included in

I am working on a shipping implementation for a checkout process.

My app has carts, cart_items, orders and order_items.

Weight and size of all items are in the database and I calculate total_weight in the order and cart models. I also have a shipping_service model with weightmin and weightmax for each shipping service + a postzone and land (country) model.

Now I would like to show on the shopping cart page only the shipping services which are conform to the weight of the cart or order.

I suppose my carts_controller should be something like:

class CartsController < ApplicationController
def show
    @cart = Cart.find(params[:id])
    @lands = Land.find(:all)
    @shippingservices = Shippingservice.where('@cart.total_weight BETWEEN ? AND ?', :weightmin, :weightmax)
end

My cart model is:

class Cart < ActiveRecord::Base
  attr_accessor :total_weight

  has_many :cart_items
  has_many :products, :through => :cart_items
  has_many :lands
  has_many :shipping_services, :through => :postzones

  def total_weight
    cart_items.inject(0) {|sum, n| n.weight * n.amount + sum}
  end
end

My land model is

class Land < ActiveRecord::Base
  has_many :shippingservices, :through => :postzones
  has_many :postzones
  has_many :carts
end

My shipping_service model is:

class Shippingservice < ActiveRecord::Base
  has_many :lands, :through => :postzones
  has_many :postzones
  has_many :carts
  has_many :orders
end

My postzone model is:

class Postzone < ActiveRecord::Base
  belongs_to :shippingservice
  belongs_to :land
end

The postzone table has foreign keys for lands and shipping_services.

Latter I would like to implement two selector fields: one for ship_to_countries and one for shipping_services, with the second selector being populate only with entries related to the entry selected in the first selector.

I had already this working inside the carts_controller:

@shippingservices = Shippingservice.includes(:lands, :postzones).where('postzones.land_id = ?', Land.first.id) 

Which load only shipping services for a specific country into the second selector. But I do not know how to combine the two where clauses relative to weight and postzone into one query.

Any help is very much appreciated!

Thank you in advance.

inside modal form_for submit not working in rails?

when i submit form submit doesn't go to reject_permission. error is URL something wrong like this

http://localhost:3000/permissions?utf8=%E2%9C%93&_method=patch&authenticity_token=hThIutas1j22xz6lNlBGZ%2BcK1h9GFacea9Jb%2BZ8ex0KSX74kz6NqV0atyoohRsuyvnzk%2FYdPS3yw4jCjbXFeag%3D%3D&id=4&%2Fpermissions%2Freject_permission%5Brejected_reason%5D=&commit=Reject

my view

 <%= link_to 'Reject',  '#', 'data-target' => "#editpermission",'data-toggle' => 'modal' ,
'data-id' => "#{permission.id}",class: "edit btn btn-danger btn-sm" %>
  <%= render 'edit_permission_modal'%>
 <script type="text/javascript">

    $(document).on("click",".edit",function(){
      var permissionId = $(this).data('id');


      $(".modal-body #permissionId").attr("value",permissionId);


    })
   </script>

edit_permission_modal.html.erb

<div class="modal fade" id="editpermission" role="dialog">
            <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
               <div class="modal-header">
               </div>
               <div class="modal-body">
                  <%= form_for reject_path,multipart: true, method: :patch do |f| %>
                  <input type="hidden" name="id" id="permissionId" class="form-control" value="">
                  <%=f.text_field :rejected_reason,class: "form-control"%>
               </div>
               <div class="modal-footer">
                  <%= f.submit 'Reject', class: "btn btn-danger btn-sm" %>
               </div>
               <%end%>
            </div>
            </div>
</div>

controller

    class PermissionsController < ApplicationController
     before_action :set_permission, only: [:show, :edit, :update, :destroy,:accept_permission]
    def reject_permission
            puts "reject_permission"
        end
end

routes

resources :permissions
patch 'permissions/reject_permission',to: 'permissions#reject_permission', as: :reject

Output

Select2 I18n Placeholder Rails

I am looking to add translation to my select2 dropdowns, I have the following: View

    <%= f.collection_select(:guest_id, User.all, :id, :full_name, {}, class: "selectpicker", placeholder: true, multiple: true) %>

<SCRIPT>  $(document).ready(function () {
        $('#invitation_guest_id').select2({
            language: $('html').attr('lang'),
            placeholder: I18n.t('js.posts.select2.contact_name_dist'),
            minimumInputLength: 3
        });
    });
</SCRIPT>

I have a file Translation.js with the key contact_name_dist translated in many languages. For some reason, Rails only returns the english translation. Good thing, is it means it can read my file. But probably not picking up the language instruction. Any argument missing ?

dimanche 16 décembre 2018

Deprecation warning - datepicker

I have the following error in my Chrome console:

Deprecation warning: use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.

I have been searching for hours now, does anybody know how to remove/fix this error? It is related to datepicker.

Rails dataTable internationalization

I am looking to display datatable with the fields shown in the current local, instead of english. I saw on the datatables.net that I should just add languages before the options, but when I do so, the options totally disapears and the table shows as plain, without the search, entries, etc.

I did the following in my xxx.coffee:

  $("#table_cadeau").dataTable({
    "language": {
      "searching": true
      "limit": 5
      "lengthMenu": [[5,10,25,50, 100,250,-1],[5,10,25,50, 100,250,"All"]]

    }})

Does anyone knows what should be added or modified please ? Thanks!

vendredi 14 décembre 2018

Why is Rails not finding my jbuilder template or not rendering it?

I have a route that looks like this:

resources :property_searches, :path => 'search'

That generates these routes:

 property_searches GET    /search(.:format)                                                             property_searches#index
                   POST   /search(.:format)                                                             property_searches#create
new_property_search GET    /search/new(.:format)                                                         property_searches#new
edit_property_search GET    /search/:id/edit(.:format)                                                    property_searches#edit
    property_search GET    /search/:id(.:format)                                                         property_searches#show
                    PUT    /search/:id(.:format)                                                         property_searches#update
                    DELETE /search/:id(.:format)                                                         property_searches#destroy

This is what I have in my PropertySearchesController#Index:

@properties = Property.first(5) #This is just a test

respond_to do |format|
  format.html {}

  format.json {}

  format.fullsearch do
    render :formats => [ :js ]
  end

  format.livesearch do

  end

  format.filtersearch do
    render :formats => [ :quicksearch ]
  end
end

Then in my views/property_searches/index.json.jbuilder, I have the following:

json.properties do
  json.array!(@properties) do |property|
    json.name property.name
  end
end

When I visit /search.json in my address bar, this is what I get in my logs:

Started GET "/search.json" for 127.0.0.1 at 2018-12-14 14:22:32 -0500
Processing by PropertySearchesController#index as JSON

Completed 500 Internal Server Error in 993.8ms
** [Raven] Missing template property_searches/index, application/index with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in:
  * "/hj-project/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/kaminari-0.15.1/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/comfortable_mexican_sofa-1.8.5/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/formatted_form-2.1.2/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/declarative_authorization-0.5.7/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/bundler/gems/comfy-blog-fcf9e4e88948/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/xray-rails-0.3.1/app/views"
 excluded from capture due to environment or should_capture callback

ActionView::MissingTemplate (Missing template property_searches/index, application/index with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in:
  * "/hj-project/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/kaminari-0.15.1/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/comfortable_mexican_sofa-1.8.5/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/formatted_form-2.1.2/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/declarative_authorization-0.5.7/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/bundler/gems/comfy-blog-fcf9e4e88948/app/views"
  * "/.rvm/gems/ruby-2.3.0@hjproject/gems/xray-rails-0.3.1/app/views"
):
  actionpack (3.2.22.5) lib/action_view/path_set.rb:58:in `find'

I also tried putting this in my respond_to block instead:

  format.json { render json: {properties: []} }

And even though it doesn't produce the same error, when I go to the page I literally just see this on the page:

{"properties":[]}

It doesn't show me the values within @properties that I set.

What is causing this and how do I fix it?

jeudi 13 décembre 2018

edit action on popup bootrap modal in rails?

i am beginner .i want to edit action on bootstrap popup modal but view is working edit action is not working

my view

  <%@leaves.each do |leave| %>
 <td><a href="#" data-toggle="modal" data-target="#myModal-<%= leave.id %>"></td>        
   <div class="modal fade" id="myModal-<%= leave.id %>" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header"> 
 </h4>
        </div>
        <div class="modal-body">
            <%= form_for(@leave, url: leave_path)  do |f| %>  
            <%=f.text_field :rejected_reason%>
             <%=f.submit'update'%>
                <% end -%>
        </div>
        <div class="modal-footer ">        
            <%=link_to 'Reject',reject_leave_path(:id=>leave.id), method: :patch,class: "btn btn-danger btn-sm "%>       
        </div>
                           </td>
                           </tr>
                           <% end %>  

my routes

 Rails.application.routes.draw do
    resources :leave      
    end

Active Merchant-Paypal Express implementation does not pass order_items and price

I am trying to implement Paypal Express Checkout to a Rails App. I would like to save my order with all the client's details in my orders database and send the customer to PayPal, where he should accept the payment and be redirected to my website.

The PayPal merchant is going to be localized in the EU. I specify this, since I read that Active Merchant has or had some restrictions in this regard.

I am able to get directed to PayPal, login, return to my website where express_token and express_payer_id are written to the orders database.

Unfortunately the only parameter which appears to be handed over to PayPal is :description => 'Books', nothing else appears on PayPal's Sandbox page and no payment is executed.

The relative part of my checkout_controller is:

class CheckoutController < ApplicationController
  before_filter :initialize_cart

  def place_order
    @order = Order.new(params[:order])
    @order.customer_ip = request.remote_ip 
    populate_order
    if @order.save
      checkout_paypal
      @order.status == 'processed'
    else
      render :action => 'index'
    end
  end

The private checkout_paypal action in the same controller is:

  def checkout_paypal
    price_in_cents = (@order.total * 100).round

    options = {:order_id => @order.id, 
              # :items => @order.order_items,
              :handling => 0,
              :tax => 0,
              :currency => "EUR",
              :email => @order.email, 
              :address => { :address1 => @order.ship_to_address, 
                            :city => @order.ship_to_city, 
                            :country => @order.ship_to_country, 
                            :zip => @order.ship_to_postal_code 
                          } , 
              :description => 'Books',
              :ip => @order.customer_ip,
              :return_url => checkout_success_url(@order), # return here if payment success
              :cancel_return_url => checkout_error_url(@order) # return here if payment failed
              }

    paypal_response = GATEWAY.setup_purchase(price_in_cents, options)
    if paypal_response.success? 
      @order.status = 'processed' 
    else 
      @order.error_message = response.message 
      @order.status = 'failed' 
    end 
    @order.express_token = paypal_response.token # save paypal token to db
    @order.save
    redirect_to GATEWAY.redirect_url_for(paypal_response.token) and return  # redirect to paypal for payment
  end

The private populate_order action in the same controller is:

  def populate_order
    @cart.cart_items.each do |cart_item|
      order_item = OrderItem.new(:product_id => cart_item.product_id, :price => cart_item.price, :amount => cart_item.amount)
      @order.order_items << order_item
    end
  end
end

When I add :items => @order.order_items to the checkout_paypal options

I get https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token= with No token passed

and status: failed

as well as error_message ok written to the orders database.

Started POST "/checkout/place_order" for 127.0.0.1 at Thu Dec 13 10:13:22 +0100 2018
Processing by CheckoutController#place_order as HTML
  Parameters: {"utf8"=>"✓", "commit"=>"Paypal Express", "authenticity_token"=>"somestring=", "order"=>{"ship_to_last_name"=>"Mustermann", "ship_to_address"=>"ESpachstr. 1", "ship_to_city"=>"Freiburg", "email"=>"mustermann@example.de", "ship_to_postal_code"=>"79111", "ship_to_first_name"=>"Hans", "ship_to_country"=>"Germany", "phone_number"=>"213412341234"}}
  Cart Load (0.3ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 3]]
  CartItem Load (0.3ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 3
  SQL (0.1ms)  BEGIN
  SQL (1.0ms)  INSERT INTO `orders` (`created_at`, `customer_ip`, `email`, `error_message`, `express_payer_id`, `express_token`, `phone_number`, `ship_to_address`, `ship_to_city`, `ship_to_country`, `ship_to_first_name`, `ship_to_last_name`, `ship_to_postal_code`, `status`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["created_at", Thu, 13 Dec 2018 09:13:22 UTC +00:00], ["customer_ip", "127.0.0.1"], ["email", "mustermann@example.de"], ["error_message", nil], ["express_payer_id", nil], ["express_token", nil], ["phone_number", "213412341234"], ["ship_to_address", "ESpachstr. 1"], ["ship_to_city", "Freiburg"], ["ship_to_country", "Germany"], ["ship_to_first_name", "Hans"], ["ship_to_last_name", "Mustermann"], ["ship_to_postal_code", "79111"], ["status", "open"], ["updated_at", Thu, 13 Dec 2018 09:13:22 UTC +00:00]]
  SQL (1.0ms)  INSERT INTO `order_items` (`amount`, `created_at`, `order_id`, `price`, `product_id`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?)  [["amount", 2], ["created_at", Thu, 13 Dec 2018 09:13:22 UTC +00:00], ["order_id", 14], ["price", 5], ["product_id", 3], ["updated_at", Thu, 13 Dec 2018 09:13:22 UTC +00:00]]
   (0.4ms)  COMMIT
  SQL (0.1ms)  BEGIN
   (0.5ms)  UPDATE `orders` SET `updated_at` = '2018-12-13 09:13:23', `status` = 'failed', `error_message` = 'OK' WHERE `orders`.`id` = 14
   (0.4ms)  COMMIT
Redirected to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=
Completed 302 Found in 1346ms (ActiveRecord: 4.0ms)

When I do not add it I proceed:

Started POST "/checkout/place_order" for 127.0.0.1 at Thu Dec 13 10:18:12 +0100 2018
Processing by CheckoutController#place_order as HTML
  Parameters: {"authenticity_token"=>"somestring=", "utf8"=>"✓", "order"=>{"ship_to_city"=>"Freiburg", "ship_to_postal_code"=>"79111", "ship_to_country"=>"Germany", "ship_to_address"=>"ESpachstr. 1", "phone_number"=>"124513451345134", "ship_to_first_name"=>"Hans", "email"=>"mustermann@example.de", "ship_to_last_name"=>"Mustermann"}, "commit"=>"Wire transfer"}
  Cart Load (0.3ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 3]]
  CartItem Load (0.4ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 3
  SQL (0.1ms)  BEGIN
  SQL (2.1ms)  INSERT INTO `orders` (`created_at`, `customer_ip`, `email`, `error_message`, `express_payer_id`, `express_token`, `phone_number`, `ship_to_address`, `ship_to_city`, `ship_to_country`, `ship_to_first_name`, `ship_to_last_name`, `ship_to_postal_code`, `status`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["created_at", Thu, 13 Dec 2018 09:18:12 UTC +00:00], ["customer_ip", "127.0.0.1"], ["email", "mustermann@example.de"], ["error_message", nil], ["express_payer_id", nil], ["express_token", nil], ["phone_number", "124513451345134"], ["ship_to_address", "ESpachstr. 1"], ["ship_to_city", "Freiburg"], ["ship_to_country", "Germany"], ["ship_to_first_name", "Hans"], ["ship_to_last_name", "Mustermann"], ["ship_to_postal_code", "79111"], ["status", "open"], ["updated_at", Thu, 13 Dec 2018 09:18:12 UTC +00:00]]
  SQL (1.1ms)  INSERT INTO `order_items` (`amount`, `created_at`, `order_id`, `price`, `product_id`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?)  [["amount", 2], ["created_at", Thu, 13 Dec 2018 09:18:12 UTC +00:00], ["order_id", 15], ["price", 5], ["product_id", 3], ["updated_at", Thu, 13 Dec 2018 09:18:12 UTC +00:00]]
   (0.7ms)  COMMIT
  SQL (0.2ms)  BEGIN
   (0.6ms)  UPDATE `orders` SET `express_token` = 'EC-sandboxtoken', `status` = 'processed', `updated_at` = '2018-12-13 09:18:13' WHERE `orders`.`id` = 15
   (0.8ms)  COMMIT
Redirected to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-sandboxtoken
Completed 302 Found in 1410ms (ActiveRecord: 7.1ms)

processed is written to @order.status as well as EC-sandboxtoken to @order.express_token and sandboxpayerid to @order.express_payer_id, but nothing shows up in the Paypal Express window:

Screenshot of the customer PayPal window

This is the output of the redirect:

Started GET "/checkout/success/15?token=EC-sandboxtoken&PayerID=sandboxpayerid" for 127.0.0.1 at Thu Dec 13 10:22:59 +0100 2018
Processing by CheckoutController#success as HTML
  Parameters: {"PayerID"=>"sandboxpayerid", "id"=>"15", "token"=>"EC-sandboxtoken"}
  Cart Load (0.3ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 3]]
  Order Load (0.4ms)  SELECT `orders`.* FROM `orders` WHERE `orders`.`id` = ? LIMIT 1  [["id", "15"]]
  SQL (0.1ms)  BEGIN
  OrderItem Load (0.3ms)  SELECT `order_items`.* FROM `order_items` WHERE `order_items`.`order_id` = 15
   (0.3ms)  UPDATE `orders` SET `updated_at` = '2018-12-13 09:22:59', `express_payer_id` = 'sandboxpayerid' WHERE `orders`.`id` = 15
   (0.7ms)  COMMIT
  Product Load (0.4ms)  SELECT `products`.* FROM `products` WHERE `products`.`id` = 3 LIMIT 1
  Rendered checkout/success.html.erb within layouts/application (2.8ms)
  Rendered layouts/_header.html.erb (0.2ms)
  Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 17ms (Views: 9.5ms | ActiveRecord: 2.5ms)

How can I get this to work and does Active Merchant + Paypal Express Checkout + EU merchant work anyway?

mercredi 12 décembre 2018

PayPal Express return configuration produces couldn't find Order without an ID

I am working on a PayPal express integration and successfully connect to PayPal and place the payment, but on return I get:

ActiveRecord::RecordNotFound in CheckoutController#success

Couldn't find Order without an ID

The actions in my controller are:

def place_order
  @order = Order.new(params[:order])
  @order.customer_ip = request.remote_ip 
  populate_order
  if @order.save
    checkout_paypal
  else
    render :action => 'index'
  end
end

def success
  @page_title = 'Thank You!'
  @order = Order.find(params[:order])
  @order.express_payer_id = params[:PayerID]
  @order.save
end

private 

def checkout_paypal
  paypal_response = ::GATEWAY.setup_purchase(
    (@order.total * 100).round, # paypal amount is in cents
    :ip => request.remote_ip,
    :return_url => checkout_success_url(@order),
    :cancel_return_url => checkout_error_url(@order)
  )
  @order.express_token = paypal_response.token
  @order.save
  redirect_to ::GATEWAY.redirect_url_for(paypal_response.token) and return
end

routes are:

match '/checkout/place_order', :to => 'checkout#place_order'
match '/checkout/success',     :to => 'checkout#success'
match '/checkout/error',       :to => 'checkout#error'

how credit card interest works

I am working in bank a want more knowlege about this field is there any one how can help me on this topic Credit Card Processing

How to set Paypal Express url for checkout in rails app

I am working on the integration of Paypal Express payments. I am adapting a Standard checkout and I am using the active-merchant gem. Set up should be something like response=gateway.setup_purchase(price, details), where details are all the parameter which PayPal requires. The express gateway requires a return_url and cancel_return_url.

When I try to execute the payment through a submit button I get:

Order xx failed with error message undefined method `thank_you_checkout_url' for #<Order:0x1081e1bb8> 

In my order model I have the following parts:

#app/models/order.rb

def process
  process_with_active_merchant
  save!
  self.status == 'processed'
end

private
def process_with_active_merchant
  ActiveMerchant::Billing::Base.mode = :test
  gateway = ActiveMerchant::Billing::PaypalExpressGateway.new( 
    :login     => 'sandbox-account', 
    :password  => 'sandbox-password', 
    :signature => "sandbox-secret"

    params = { 
    :order_id => self.id, 
    :email => email, 
    :address => { :address1 => ship_to_address, 
                  :city => ship_to_city, 
                  :country => ship_to_country, 
                  :zip => ship_to_postal_code 
                } , 
    :description => 'Books', 
    :ip => customer_ip,
    :return_url => thank_you_checkout_url(@order), # return here if payment success
    :cancel_return_url => index_checkout_url(@order) # return here if payment failed
}
  response = gateway.setup_purchase((@order.total * 100).round(2), params)
  if response.success? 
    self.status = 'processed' 
  else 
    self.error_message = response.message 
    self.status = 'failed' 
  end 
end 

The method is called in the checkout controller

def place_order
  @order = Order.new(params[:order])
  @order.customer_ip = request.remote_ip 
  populate_order
  ...
  @order.process
  ...
end

def thank_you
 ...
end

How can I get this to work? Thank you in advance!

Reading xhtml file with Nokogiri give tag invalid errors

I am using rails 5 with ruby 2.3
I am using gem nokogiri (1.8.5) to read my xml, svg and xhtml files.

While reading my xhtml file the nokogiri gives me following errors.

> [#<Nokogiri::XML::SyntaxError: 8:159: ERROR: Tag x3d invalid>,
> #<Nokogiri::XML::SyntaxError: 9:21: ERROR: Tag scene invalid>, #<Nokogiri::XML::SyntaxError: 10:37: ERROR: Tag navigationinfo invalid>, #<Nokogiri::XML::SyntaxError: 11:45: ERROR: Tag background
> invalid>, #<Nokogiri::XML::SyntaxError: 14:47: ERROR: Tag viewpoint
> invalid>, #<Nokogiri::XML::SyntaxError: 15:75: ERROR: Tag transform
> invalid>, #<Nokogiri::XML::SyntaxError: 16:69: ERROR: Tag shape
> invalid>, #<Nokogiri::XML::SyntaxError: 17:55: ERROR: Tag appearance
> invalid>, #<Nokogiri::XML::SyntaxError: 19:81: ERROR: Tag
> commonsurfaceshader invalid>]

is there any way to add custom tags to nokogiri, so that I can parse my xhtml and fetch the useful data from it.
In my xhtml I am using x3d tags also
Thanks in advance

mardi 11 décembre 2018

I get a Undefined method '-' NilClass error when I am trying to program something for my game. It is in this function and I do not know what is wrong

I get a Undefined method '-' NilClass error when I am trying to program something for my game. It is in this function and I do not know what is wrong

This is my code … enter image description here

Rspec 3.8 before block not deleting record

In app/models/car.rb the class method stock looks in part like this:

 def self.stock
   raise Exception, "Property amount not set" if Property.get(:amount).nil?
   ...
 end

This Property is accessable by the user through all CRUD operations. I now want to test that if that Property is truly deleted an standard expection should be thrown. Therefore i created in my rspec model the following example group

describe '.stock' do

  describe 'if property is not set' do
    before(:all) {Property.where(name: 'amount').map(&:destroy)}
    it 'raises an exception' do
      expect{Car.stock}.to raise_error (Exception)
    end 
    after (:all) {Property.create! name: 'amount', value: 10}
  end 

  describe 'if property is set' do
    before (:all) do  
      create :car_listed
      create :car_sold
    end 
    it 'calculates the correct amount of sellable cars' do
      amount = 10 - Car.where(state: "sold")
      expect(Car.stock).to eq(amount)
    end 
  end 
end 

I delete all Properties first with that specific name, i expect the exception to be trown and then i create it again. There are some properties which are not going to change a lot during tests. So database_cleaner does not truncate the properties table. It got set through a seeds file.

config.before(:suite) do
  DatabaseCleaner.strategy = :truncation, {except: %w[properties]}
end

The test however fails with

Car
 .stock
   if property is set
    calculates the correct amount of sellable cars
   if property is not set
      raises an exception (FAILED - 1)

 Failures:

  1) Car.stock if property is not set not set raises an exception
      Failure/Error: expect{Car.stock}.to raise_error (Exception)
      expected Exception but nothing was raised
      # ./spec/models/car_spec.rb: `block (4 levels) in <top (required)>'

My question is now how do i have to delete this property properly ((:), so that my exception gets raised.

lundi 10 décembre 2018

Validation not passing for 'SyntaxError syntax error, unexpected tIDENTIFIER, expecting kEND):'

I am working on a checkout routine for a Rails webshop. Everything is working, but following a tutorial I placed a validation which throws a SyntaxError syntax error, unexpected tIDENTIFIER, expecting kEND): error.

When I uncomment it, everything works, but I still would like to implement a validation in this place.

The error is related to lines 17, 46 and 47 in the controller and 10 in the model.

The relative action in my controller is:

class CheckoutController < ApplicationController

  def place_order 
    @page_title = "Checkout" 
    @order = Order.new(params[:order])
    @order.customer_ip = request.remote_ip 
    populate_order ### LINE 17

    ...
  end

  private 
  def populate_order
    @cart.cart_items.each do |cart_item|
      order_item = OrderItem.new(:product_id => cart_item.product_id, :price => cart_item.price, :amount => cart_item.amount)  ### LINE 46
      @order.order_items << order_item ### LINE 47
    end
  end
end 

The order_item model is:

class OrderItem# < ActiveRecord::Base
  attr_accessible :amount, :price, :product_id, :order_id
  belongs_to :order
  belongs_to :product
  def validate

errors.add(:amount, "should be one or more") unless amount.nil? || amount > 0
 ### LINE 10

     errors.add(:price, "should be a positive number") unless price.nil? || price > 0.0
  end
end

Not even stackoverflow lets me put in this line correctly

The error messages for line 10 and the pass with line 10 uncommented are as follows

Started POST "/checkout/place_order" for 127.0.0.1 at Tue Dec 11 08:03:05 +0100 2018
Processing by CheckoutController#place_order as HTML
  Parameters: {"order"=>{"email"=>"test@example.tld", "ship_to_last_name"=>"Smith", "phone_number"=>"123451234134", "ship_to_first_name"=>"John", "ship_to_country"=>"United States of America", "ship_to_postal_code"=>"12345", "ship_to_address"=>"Somewhere Avenue", "ship_to_city"=>"Nowheretorn"}, "utf8"=>"✓", "authenticity_token"=>"xxxxx=", "commit"=>"Place Order"}
  Cart Load (0.4ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 3]]
  CartItem Load (0.4ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 3
Completed 500 Internal Server Error in 5ms

SyntaxError (/Users/devaccount/Development/REPRO/webapp/app/models/order_item.rb:10: syntax error, unexpected tIDENTIFIER, expecting kEND):
  app/controllers/checkout_controller.rb:46:in `populate_order'
  app/controllers/checkout_controller.rb:45:in `populate_order'
  app/controllers/checkout_controller.rb:17:in `place_order'


Started POST "/checkout/place_order" for 127.0.0.1 at Tue Dec 11 08:03:29 +0100 2018
Processing by CheckoutController#place_order as HTML
  Parameters: {"order"=>{"email"=>"test@example.tld", "ship_to_last_name"=>"Smith", "phone_number"=>"123451234134", "ship_to_first_name"=>"John", "ship_to_country"=>"United States of America", "ship_to_postal_code"=>"12345", "ship_to_address"=>"Somewhere Avenue", "ship_to_city"=>"Nowheretorn"}, "utf8"=>"✓", "authenticity_token"=>"xxxxx=", "commit"=>"Place Order"}
  Cart Load (0.2ms)  SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = ? LIMIT 1  [["id", 3]]
  CartItem Load (0.4ms)  SELECT `cart_items`.* FROM `cart_items` WHERE `cart_items`.`cart_id` = 3
  SQL (0.1ms)  BEGIN
  SQL (1.4ms)  INSERT INTO `orders` (`created_at`, `customer_ip`, `email`, `error_message`, `phone_number`, `ship_to_address`, `ship_to_city`, `ship_to_country`, `ship_to_first_name`, `ship_to_last_name`, `ship_to_postal_code`, `status`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["created_at", Tue, 11 Dec 2018 07:03:29 UTC +00:00], ["customer_ip", "127.0.0.1"], ["email", "test@example.tld"], ["error_message", nil], ["phone_number", "123451234134"], ["ship_to_address", "Somewhere Avenue"], ["ship_to_city", "Nowheretorn"], ["ship_to_country", "United States of America"], ["ship_to_first_name", "John"], ["ship_to_last_name", "Smith"], ["ship_to_postal_code", "12345"], ["status", "open"], ["updated_at", Tue, 11 Dec 2018 07:03:29 UTC +00:00]]
  SQL (1.1ms)  INSERT INTO `order_items` (`amount`, `created_at`, `order_id`, `price`, `product_id`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?)  [["amount", 1], ["created_at", Tue, 11 Dec 2018 07:03:29 UTC +00:00], ["order_id", 7], ["price", 10], ["product_id", 13], ["updated_at", Tue, 11 Dec 2018 07:03:29 UTC +00:00]]
   (0.5ms)  COMMIT
  SQL (0.1ms)  BEGIN
   (0.3ms)  UPDATE `orders` SET `updated_at` = '2018-12-11 07:03:29', `status` = 'processed' WHERE `orders`.`id` = 7
   (0.4ms)  COMMIT
  SQL (0.2ms)  BEGIN
  SQL (0.3ms)  DELETE FROM `cart_items` WHERE `cart_items`.`id` = ?  [["id", 11]]
   (0.4ms)  COMMIT
Redirected to http://localhost:3000/checkout/thank_you
Completed 302 Found in 138ms (ActiveRecord: 9.1ms)

I hope someone can point me into the right direction.

Can't Start Redmine After Installing Plugin

I just installed this plugin for my redmine: https://github.com/masweetman/issue_charts

After that, I can't go to my redmine webpage, here is the error log:

4mipkJBT

Any ideas? Thanks.

dimanche 9 décembre 2018

how to use joins query in rails?

i have two tables 1.Clients 2.Project

my model

class Project < ApplicationRecord
    belongs_to :client
end
class Client < ApplicationRecord
    has_many :projects
end

i have 3 records in my project table u can see project table https://imgur.com/a/f33McWa client table https://imgur.com/a/J62yZhf i want to display the record with client name how to write a query in my controller

My controller

class ProjectsController < ApplicationController
    def index
        @projects = #your query here
    end
end

Notification System in Rails using PublicActivity

I want to notify users when the email is sent to them using action mailer. So for that i have gemPublicActivity Not understanding how to proceed if some one can help it would be helpful.

class MailingQueue < ApplicationRecord
  include PublicActivity::Model
  tracked
  belongs_to :startup
end

class EmailJob < ApplicationJob
  queue_as :default
   def perform(investor_users)
    investor_users.find_each do |user|
       UserMailer.send_email(user).deliver_now
    end
  end
end

When usermailer function is performed in my dashboard I need to show the notification that a new mail is been received.

Dashboard controller

class DashboardController < ApplicationController
  before_action :authenticate_user!,:set_user, except: [:filter_by_sectors]
  skip_before_action :verify_authenticity_token, only: [:filter_by_sectors]

  def sector_interest_mentors
    @startups = Startup.paginate(:page => params[:page], :per_page => 4)
    @sectors = Sector.all.order('name ASC').group_by{|d| d.name[0]}
  end
end

How to implement persistent Rails shopping cart?

I am working on a shopping cart for a rails shop app and have different implementations working.

A) carts controller

class CartsController < ApplicationController

  def add
  ...
  end

  def remove
  ...
  end

  def clear
  ...
  end
end

& products, cart and cart_items models

Here I add the product through something such as:

 <%= button_to "Confirm", :controller => 'carts', :action => "add", :id => params[:id] %>

And so on

B) carts controller

class CartsController < ApplicationController

  def show
    ...
  end
end

order_items controller

class OrderItemsController < ApplicationController

  def create
    ...
  end

  def update
    ...
  end

  def destroy
    ...
  end

private
  def order_item_params
    ...
  end
end

and

products_controller

  def index
    ...
  end

& order, order_item, order_status and product models.

They all work with the database and I am able to successfully add, subtract to the shopping cart or clear the shopping cart by clicking a button.

But in both implementations site navigation inside the shop catalogue changes the shopping cart. So when adding a product on the detail page and navigating back to the catalogue page through the back button of the browser, the navigation goes back to the catalogue page, but the product is removed from the cart too.

How can I implement a shopping cart which does not change when navigating inside the shop?

vendredi 7 décembre 2018

Ruby on rails CLI 'rails s' command not working, localhost refused to connect

Tried to run rails s command on rails shell but it would not let me do it and it stops at use ctrl-c to stop and stays there for ages and doesn't get executed. I have to Ctrl-c of which allows me to exit.

When I try to connect to my localhost it says the host refused to connect. any ideas?

CLI picture

jeudi 6 décembre 2018

mercredi 5 décembre 2018

Handling session in rails

The admin has the rights to activate deactivate user account. example image link https://imgur.com/a/S9wEsQY only activated user should be login that scenario has been completed successfully(used Boolean datatype admin=true&user=false).activated user have longed in browser if admin has deactivated her account.user should not do anything automatically leave to login page how to do it?devise gem used

routes.rb

root to: 'application#home', as: :root   
  devise_for :users, controllers: { sessions: 'users/sessions',
                    registrations: 'users/registrations'
                  }

controller# application_controller.rb

class ApplicationController < ActionController::Base
    before_action :authenticate_user!
def home
end
end

model# user.rb

def is_admin?
     role == 0
    end

    def is_user?
        role == 1
    end

view# home.html.erb

<%if  current_user.is_admin?%>
<%=  render 'layouts/admin' %>
      <%else%>
<%=  render 'layouts/user' %>
<% end %>

The best way to find the data in rails times only, without dates?

For example, I am having the data

<User id: 182, day: "2018-12-10", start_time: "2018-12-04 07:00:00", end_time: "2018-12-04 19:30:00", created_at: "2018-12-04 08:15:49", updated_at: "2018-12-04 09:41:38", mechanic_id: 1, end_day: "2018-12-07">

I want to run the query to fetch the data based on start_time

User.where(condition)

The condition must be time only it will not include the date.

how to concat fixnum and string in rails?

i want to contat my static id + looping primary key id

 <% @user.each do |employee| %>
 <td><%=employee.username%></td>
   <td> <%=link_to 'activate',activate_path(id:employee.id), method: :patch ,id:"activate"+"<%=employee.id%>".to_s%></td>
     <% end %>

Rails form select for join table produces ActiveRecord::AssociationTypeMismatch

I am trying to setup the data input for a database which contains for example projects. Projects can be part of a series, have multiple curators, etc.

I either get the series form displayed with:

<%= f.collection_select :series, Series.order('word asc'), :id, :word, {}, {:class => 'select-style'} %>

with proper styling, but upon submit I get

ActiveRecord::AssociationTypeMismatch in Admin::ProjectsController#update
Series(#2212122800) expected, got String(#2183812080)

with

<%= f.select :series, Series.all.collect{ |p| [ p.word, p.id ]}, :include_blank => true, :class => "select-style" %>

CSS is not applied, but I manage to get a blank option. Submit produces the same response.

For the curators

<%= f.select :curators, options_for_select(Author.all.map{|c| [c.name, c.id]}, f.object.curators), {}, {:class => "form-control selectpicker", :include_blank => true, :multiple => true} %>

produces a multi select field with no styling and on submit I get a similar error

ActiveRecord::AssociationTypeMismatch in Admin::ProjectsController#update
Author(#2214244880) expected, got String(#2183812080)

I need to be able to apply my own CSS to the selector, have the ability for single, multiple and blank. The forms do not work and no version permits all options.

These relations are established through join-tables. My models are:

Project Model

class Project < ActiveRecord::Base
  attr_accessible :series, :curators

# Associations 
  has_and_belongs_to_many :curators, :class_name => "Author", :join_table => "projects_curators"
  has_and_belongs_to_many :series, :join_table => "projects_series" 
end

Series Model

class Series < ActiveRecord::Base
  attr_accessible :word

# Associations
  has_and_belongs_to_many :projects, :join_table => "projects_series" 

end

Curator join table

class ProjectsCurator < ActiveRecord::Base  
  attr_accessible :project_id, :author_id

# Associations
  belongs_to :project
  belongs_to :author
end

Author model

class Author < ActiveRecord::Base
  attr_accessible :name

# Associations
  has_and_belongs_to_many :projects, :join_table => "projects_curators"
end

mardi 4 décembre 2018

Adding custom form actions in ActiveAdmin

I'm using ActiveAdmin to add google OAuth credentials to a record. The client ID and Client Secret are added via record/1/edit, and I use those to generate a link to allow access. This link appears in record/view. I am trynig to find a way for the Administrator to enter the code returned by google oauth into the portal so that I can use it to generate credentials.

My current attempt looks something like this

row "Code from Google OAuth" do form do |f| label "Google Auth Code:" input :code, :label => "Code", :hint => "Code returned by google auth" f.action :submit end

I get an "undefined method: action" error form this code. Any ideas on how to return user input as a parameter?

Rspec request spec examine response body

Since rspec 3.5 request specs are used to test controller behaviour plus route testing and the correct rendering of the view with the content. The last part troubles me a bit since i do not understand the thin line of what goes in the view specs to what stays in the request specs.

On relishapp i found this piece:

expect(response.body).to include("Widget was successfully created.")

which tempted me of including the following in my request test:

describe "Index page" do
  ....
  it 'includes a link to cars_parts' do
    get "/car_overview"      
    expect(response.body).to include("car_parts_path")
  end
  ....
end 

This test fails. In the view i use the link_to on the car_parts url_helper. The failing test dumps the whole response.body String and i see the car_parts_path but rspec does not see it. How do i have to change my test to make it pass without the use of capybara since it is only useable with feature specs now. And am i doing it correct after all or should this kind of test go somewhere else?

How to write a custom function in a model in ruby on rails?

i have User model class created with devise. i have role field(admin=0,user=1)in my model my db myhtml

<%if  current_user.active_admin? %>
                <%=  render 'layouts/admin' %>   
                <%else%>
                <%=  render 'layouts/user' %>
                <% end %>
            #User.rb
            def active_admin?
            #your logic here
            end

i want to login if i am a admin check role is 0 render to layouts/admin else i am a user check role is 1 render to layouts/user. how to write a code in model

Redis and Sidekiq in production on Ubuntu 16.04 using systemd and Deployment with Capistrano

I am deploying sidekiq in ubuntu 16.04 using systemd service with Capistrano.

Sidekiq system service file /lib/systemd/system/sidekiq.service

#
# systemd unit file for CentOS 7, Ubuntu 15.04
#
# Customize this file based on your bundler location, app directory, etc.
# Put this in /usr/lib/systemd/system (CentOS) or /lib/systemd/system (Ubuntu).
# Run:
#   - systemctl enable sidekiq
#   - systemctl {start,stop,restart} sidekiq
#
# This file corresponds to a single Sidekiq process.  Add multiple copies
# to run multiple processes (sidekiq-1, sidekiq-2, etc).
#
# See Inspeqtor's Systemd wiki page for more detail about Systemd:
# https://github.com/mperham/inspeqtor/wiki/Systemd
#
[Unit]
Description=sidekiq
# start us only once the network and logging subsystems are available,
# consider adding redis-server.service if Redis is local and systemd-managed.
After=syslog.target network.target

# See these pages for lots of options:
# http://0pointer.de/public/systemd-man/systemd.service.html
# http://0pointer.de/public/systemd-man/systemd.exec.html
[Service]
Type=simple
WorkingDirectory=/opt//current
# If you use rbenv:
# ExecStart=/bin/bash -lc 'bundle exec sidekiq -e production'
# If you use the system's ruby:
ExecStart=/usr/local/bin/bundle exec sidekiq -e production -C config/sidekiq.yml -L log/sidekiq.log
User=deploy
Group=deploy
UMask=0002

# if we crash, restart
RestartSec=1
Restart=on-failure

# output goes to /var/log/syslog
StandardOutput=syslog
StandardError=syslog

# This will default to "bundler" if we don't specify it
SyslogIdentifier=sidekiq

[Install]
WantedBy=multi-user.target

But when start the sidekiq service using below command it not showing any error:

sudo systemctl start/stop sidekiq

In the status it throwing an error with an exit code sudo systemctl status sidekiq

● sidekiq.service - sidekiq
   Loaded: loaded (/lib/systemd/system/sidekiq.service; enabled; vendor preset: enabled)
   Active: activating (auto-restart) (Result: exit-code) since Tue 2018-12-04 01:24:39 PST; 754ms ago
  Process: 28133 ExecStart=/usr/local/bin/bundle exec sidekiq -e production -C config/sidekiq.yml -L log/sidekiq.log (code=exited, status=217/US
 Main PID: 28133 (code=exited, status=217/USER)

Dec 04 01:24:39 tt-apps-05 systemd[1]: sidekiq.service: Unit entered failed state.
Dec 04 01:24:39 tt-apps-05 systemd[1]: sidekiq.service: Failed with result 'exit-code'.

I am not able to Identify what is the problem here can any one help me.

lundi 3 décembre 2018

Railss I18n and time-date

I have the following in a simple_form:

<div class='input-group date' id='datetimepickerA'>
          <%= f.text_field (:start), :class => "form-control" %>
          <span class="input-group-addon">
          <span class="glyphicon glyphicon-calendar"></span>
      </span>
        </div>

Which I would like to translate using i18n.l, does anybody know the right synthax please?

How to handled database using ROR?

I have faced one problem to getting values from database using RoR. I have min 10crores of data, how can i get all the data using single query and min response time?

I handled some customer info its nearly 10crores of data I want to get all the customer name during particular time period(we are using MySQL)

dimanche 2 décembre 2018

Difference between [:key] and ["key"] in ruby [duplicate]

I want to know the difference between [:key] and ["key"]. Like when we get params in controller by form. If we iterate them like params[:key] or params["key"]

Both behave same. So what the difference in them if any?

Another thing which I can't differentiate till yet and not get any major difference between

:key => value and key: value

Please tell me their differences

How do I refactor this bulky set of if statements?

I have the following code that works, but I would like it to be more DRY and elegant. It feels ugly with lots of code smells.

Ideally I don't want to use CASE statements because that doesn't feel quite ruby-ish either.

if @property_status.eql? :rent
  if @property_type.eql? :residential
    @results = @search.results.for_rent.residential.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  elsif @property_type.eql? :commercial
    @results = @search.results.for_rent.commercial.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  else
    @results = @search.results.for_rent.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  end
elsif @property_status.eql? :sale
  if @property_type.eql? :residential
    @results = @search.results.for_sale.residential.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  elsif @property_type.eql? :commercial
    @results = @search.results.for_sale.commercial.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  else
    @results = @search.results.for_sale.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
  end
else
  @results = @search.results.order("#{ @sort_by } #{ @sort_order }").all.paginate(page: @page, per_page: @per_page)
end

Thoughts?

samedi 1 décembre 2018

How do I find all the records that have a specific value of an association?

I have a property model that belongs_to :property_type.

I would like to create a scope on my Property model that finds all the records of a specific property_type.

How do I find all the property records with property_type.name == "Residential"?

I have tried the following:

> Property.where('property_type.name = "Residential"').count
   (5.4ms)  SELECT COUNT(*) FROM "properties" WHERE (property_type.name = "Residential")
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property_type"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (property_type.name...

Also this:

> Property.where('property_types.name = "Residential"').count
   (1.8ms)  SELECT COUNT(*) FROM "properties" WHERE (property_types.name = "Residential")
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property_types"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (property_types.nam...