vendredi 30 novembre 2018

Add padding to bootstrap elements

Rails 3.2
Bootstrap 3

In my view (app/views/users/password_expired/show.html.slim), I have:

- content_for :page_header do
     = t('users.passwords.create_password')
   = form_for(resource, as: resource_name, url: [resource_name, :password_expired], html: {method: :post, class: "form-horizontal new_user"}) do |f|
     .form-horizontal-column.wide
       .form-group
         = devise_error_messages!
       .form-group style="width: 600px"
         = f.label :current_password, t('users.passwords.current_password')
         = f.password_field :current_password
       .form-group style="width: 600px"
         = f.label :password, t('users.passwords.new_pass')
         = f.password_field :password
       .form-group style="width: 600px"
         = f.label :password_confirmation, t('users.passwords.confirm_new_password')
         = f.password_field :password_confirmation
       div= f.submit t('users.passwords.change_my_password'), :class => "btn btn-primary btn-lg"
     .form-horizontal-column.shared-links

I was expecting to see some padding, in between the labels/input fields, and the left side of the form, but I don't have any. It seems all the other forms are working fine.

How can I added some padding, to the left of the form-group, without modifying the bootstrap style, as the latter is working everywhere else?

How to use data-image

image is not displaying. i have side bar image in my app/assets/images/sidebar-4.jpg.but did not show. tell me if there something wrong in my code.i am a beginner in ROR

dashboard.html.erb
    <div class="sidebar" data-color="purple" data-background-color="black" data-image="/assets/sidebar-4.jpg"></div>
    my image https://imgur.com/a/QikMJJS

mercredi 28 novembre 2018

Two scopes with the same :as in rails

I have some rails 3 routes that worked perfectly, for versioning an API with different module:

Rails.application.routes.draw do
  scope module: :v2, constraints: Constraints::ApiVersion.new(versions: [2, 2.1], default: false) do
    scope 'feedback/:id' do
      get 'summary', controller:'summary', action: 'summary', as: 'response_summary'
    end
  end

  scope module: :v1, constraints: Constraints::ApiVersion.new(versions: 1, default: true) do
    scope 'feedback/:id' do
      get 'summary', controller:'summary', action: 'summary', as: 'response_summary'
    end
  end
end

But now in rails 5, I get this error:

Invalid route name, already in use: 'response_summary' (ArgumentError) You may have defined two routes with the same name using the :as option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with resources as explained here: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created

Is there anyway to keep the :as the same in Rails 5?

Rspec Test CanCan AbilityClass not building rules in Rails3.2

In my Test environment Cancan does not build its rules.

ability.rb

class Ability
 include CanCan::Ability

  def initialize(user)
    user ||= User.new 

    if user.is_admin?
      can :manage, :all
    end
    ....
  end
 end

When i start the development console and i do the following

 u = User.where(role: "admin").first
 u.ability.can?(:read, Order)        #true
 a = Ability.new(u)
 a.instance_values["rules"]          #gives [0] #<CanCan::Rule:0x000055f2637ece48 @match_all=false, @base_behavior=true, @actions=[:read], @subjects=[Order(id: integer, ....

shows that everything works fine. The rules are set. Doing the same in rails c test the a.instance_values["rules"] is empty

 u = User.where(role: "admin").first
 u.ability.can?(:read, Order)        #false
 a = Ability.new(u)
 a.instance_values["rules"]          #gives [] 

As a result the test

RSpec.describe Ability do
  describe 'User' do
    describe "abilities" do
      context "when is an  Admin" do
       subject(:admin){ AdminAbility.new(create(:admin_user)) }
         it do  
           puts admin.can? :read, Order #false
           puts admin.ability.can? :read, Order #false
           expect(admin).to be_able_to(:read, Order)
         end 
         it {expect(admin).to be_able_to(:read, User) }
        end 
       end 
      end 
    end

fails not suprisingly with

** Failure/Error: it {expect(admim).to be_able_to(:read, Order)}
   expected to be able to :read Order(...)**

CanCan build the rules correctly for the development environment (I tested the FactorySetup for the roles and the Adminuser, this is not the problem)

Setup: Rails: 3.2.22.2 Rspec: 3.8 CanCan: 1.6.10

mardi 27 novembre 2018

query result in set of interval ranges in postgresql(rails)

I have a timestamp column for which i have to calculate the time difference and divide it into certain set of intervals

for time difference in hours i have written this query

 result = ActiveRecord::Base.connection.exec_query("SELECT id,(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - image_retouch_items.created_at)/3600)::INTEGER AS latency FROM image_retouch_items WHERE status= 0;");

How to get result as set of intervals(hours),like for row for which time difference lie between the range of 0-24 hr increment the count . i.e.

 interval    count
  0-24         2
 24-48         3
 48-72         0  

How to get that in single query

Devise gem - Do not allow special character in password

I have used devise gem in rails application. password format for validation I found is

PASSWORD_FORMAT_USED_CURRENTLY = /\A
  (?=.{10,})          # Must contain 10 or more characters
  (?=.*\d)           # Must contain a digit
  (?=.*[a-z])        # Must contain a lower case character
  (?=.*[A-Z])        # Must contain an upper case character
  (?=.*[[:^alnum:]]) # Must contain a symbol
/x

It works fine but I want two requirements to be fulfilled for my password 1) password must contain at least 6 letters ( it can be capital letters, small letters, digits or a combination of all ).

 PASSWORD_FORMAT = /\A
  (?=.{6,})          # Must contain 6 or more characters      
/x

2) the second criteria is that the password should not contain any special characters.

I don't know how to achieve this what I found is only that how can I make compulsory the presence of special characters but not vice versa.

Thanks in advance

lundi 26 novembre 2018

How to test if Puma is running?

Followed this tutorial

https://stormconsultancy.co.uk/blog/development/ruby-on-rails/switching-pow-puma-rails-development/

Getting "Unable to Connect" when hitting these URL's https://statrubytwotwo.dev OR http://statrubytwotwo.dev

Terminal Feedback:

MacBook-Pro-2:statrubytwotwo jn$ puma-dev
* Directory for apps: /Users/jn/.puma-dev
* Domains: test
* DNS Server port: 9253
* HTTP Server port: 9280
* HTTPS Server port: 9283
! Puma dev listening on http and https

Turnedoff and on wifi

Shutdown browser

Hit the URL

Anyone know how to test this to be sure I am hitting the server? I tried tailing it but nothing happens but what is listed above in the terminal.

If I curl:

curl -H "Host: puma-dev" localhost/status

returns

{}

Rails Datamapper (dm-rails) KeyError: key not found: "all"

I am using rails 3 with dm-rails gem.

Getting an error while searching for Model.all enter image description here

adapter: Soap
  disable_format_extenstion_in_request_url: <%= ENV['xxxxxxxxx'].inspect %>
  format: <%= ENV['xxxxxxxxx'].inspect %>
  pub_key: <%= ENV['xxxxxxxxx'].inspect %>
  app_id: <%= ENV['xxxxxxxxx'].inspect %>
  institution_name: <%= ENV['xxxxxxxxx'].inspect %>
  ssl_keystore_file: <%= ENV['xxxxxxxxx'].inspect %>
  ssl_keystore_password: <%= ENV['xxxxxxxxx'].inspect %>
  wsdl_store: <%= ENV['xxxxxxxxx'].inspect %>

Any help on this? Thanks in advance.

How to generate pdf using 'wkhtmltopdf-binary' in rails 3.22

I have account datatable for which i need to generate pdf.
However i used

gem 'wkhtmltopdf-binary'

But iam getting reponse of generated pdf only once.i.e I cannot render the attachment view after clicking print button.

Here is my controller code:

def acclose_pdf

  @hp = HpEntry.where(:HPEntryId => params[:hp_id]).last
  @test_ac = @hp.Name

   html_content = render_to_string(:action=>"acclose_pdf.html.erb",:layout=> false)
    pdf_convert = PDFKit.new(html_content,:margin_right => '0.2in',:margin_left => '0.2in',:margin_top => '0.2in',:margin_bottom => "0.1in",:page_size => "A4", :orientation => 'landscape')   
    send_data(pdf_convert.to_pdf,:filename=>"ClosedAccount.pdf", :disposition => "Attachment")


end 


And My view with Ajax:

<%= button_tag "Print" ,:class =>'btn btn-success print_ac_close_data',:id => "#{entry.HPEntryId}"%>
 <script type="text/javascript">
 $('.print_ac_close_data').click(function(){
 var hp_id = $(this).attr('id')
 var class_val = $(this).val()
 $.ajax({
  dataType: "html",        
  cache: false,
  url: "/ac_close_print",
  data: {"hp_id": hp_id},
  contentType: "application/json",
});});</script>


Can anyone help me on generating PDF attachment?

dimanche 25 novembre 2018

How to generate a expiry link in rails for edit page

I need to generate an expiry link for the edit page that will be sent to the user through the mail for one of my models. How would I do that? can anyone help me out? I have generated the mailer functionality, just need to add the expiry link in the template.

Spree installation ActiveRecord::ConnectionNotEstablished

I am trying to install Spree on an old Rails App (3.2.5) in order to set up a shop section for a webpage.

I tried different gem versions and managed to get 0.30.0 installed.

In my gem file I have:

gem 'spree', '0.30.0'
gem 'acts_as_list', '0.1.2'
gem 'paperclip', '2.3.1.1'
gem 'stringex', '1.0.3'

when I try to create the site

rails g spree:site

I get the following error:

/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:85:in `require': There was an error while trying to load the gem 'spree'. (Bundler::GemRequireError)
Gem Load Error is: ActiveRecord::ConnectionNotEstablished
Backtrace for gem load error is:
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_specification.rb:168:in `retrieve_connection'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activerecord-3.2.5/lib/active_record/connection_adapters/abstract/connection_specification.rb:142:in `connection'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activerecord-3.2.5/lib/active_record/model_schema.rb:228:in `columns'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activerecord-3.2.5/lib/active_record/model_schema.rb:248:in `column_names'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/rd_searchlogic-3.0.1/lib/searchlogic/named_scopes/ordering.rb:61:in `ordering_condition_details'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/rd_searchlogic-3.0.1/lib/searchlogic/named_scopes/ordering.rb:52:in `method_missing'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/spree_core-0.30.0/lib/spree_core/find_by_param.rb:105
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `gem_original_require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:236:in `load_dependency'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/spree_core-0.30.0/lib/spree_core.rb:47
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/spree-0.30.0/lib/spree.rb:1:in `gem_original_require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/spree-0.30.0/lib/spree.rb:1:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/spree-0.30.0/lib/spree.rb:1
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:81:in `gem_original_require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:81:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:81:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:76:in `each'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:76:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:65:in `each'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:65:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler.rb:114:in `require'
/Users/Useraccount/Development/SPREE/tst_spree_02/config/application.rb:7
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/railties-3.2.5/lib/rails/commands.rb:24:in `gem_original_require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/railties-3.2.5/lib/rails/commands.rb:24:in `require'
/Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/railties-3.2.5/lib/rails/commands.rb:24
script/rails:6:in `gem_original_require'
script/rails:6:in `require'
script/rails:6
Bundler Error Backtrace:
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:76:in `each'
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:76:in `require'
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:65:in `each'
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler/runtime.rb:65:in `require'
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/bundler-1.16.1/lib/bundler.rb:114:in `require'
from /Users/Useraccount/Development/SPREE/tst_spree_02/config/application.rb:7
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/railties-3.2.5/lib/rails/commands.rb:24:in `gem_original_require'
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/railties-3.2.5/lib/rails/commands.rb:24:in `require'
from /Users/Useraccount/.rvm/gems/ruby-1.8.7-p374@spree-test-02/gems/railties-3.2.5/lib/rails/commands.rb:24
from script/rails:6:in `gem_original_require'
from script/rails:6:in `require'
from script/rails:6

Unfortunately a newer version does not get installed on the web app and the older gems require older versions of Rails.

Why does that happen and how can I manage to get it running?

samedi 24 novembre 2018

how to complicated ruby on rails application to openshift

I have one ruby on rails application and I would like to migrate it to upshift. The ruby on rails application have some background services like: 1. qpid 2. umb 3. delayed_jobs

And we know openshift suggests that one container one process What Can I do for this part?

vendredi 23 novembre 2018

How to use material css classes in wiked_pdf gem in Rails

I want to use the material css classes in my generated pdf file, please guide me how can I use these classes like... m12, col, red etc

How to represent a method call that's through inheritance in a sequence diagram? (Ruby)

class FirstClass < SecondClass; end

class SecondClass
  include ThirdClass 
end

class ThirdClass 
  def inherited_method 
  end
end

How would I represent FirstClass.new.inherited_method in a UML sequence diagram? I want to explicitly show that the method is inherited from the ThirdClass (because I'm going to draw a parallel to another sequence that is also using the same inherited method).

jeudi 22 novembre 2018

How do I manage has_and_belongs_to_many relation for nested fields in Ruby on Rails

class Resume < ActiveRecord::Base
  has_many :user_skills, :dependent => :destroy
  accepts_nested_attributes_for :user_skills, :allow_destroy => true, :reject_if => :all_blank 
end

class UserSkill < ActiveRecord::Base
  belongs_to :resume
  has_and_belongs_to_many :technologies
end

class Technology < ActiveRecord::Base
  has_and_belongs_to_many :user_skills
end


<%= nested_form_for([:student, @resume], validate: true, :html => { :multipart => true, class: "full-width" }) do |f| %>


 ------------------------------
      Resume fields
 ------------------------------      

 <h5>User Skills</h5>
<%= f.fields_for :user_skills do |us| %>

  <%= us.label :academic_years, "Academic Years" %>
  <%= us.text_field :academic_years %>

  <%= us.label :professional_years, "Professional Years" %>
  <%= us.text_field :professional_years %>

  <%= us.fields_for :technologies do |tech| %>

     <%= tech.collection_select :name, Technology.all, :id, :name, { prompt: "Select Technology"}, { :multiple => true, :size => 10} %> 

  <% end %>

   <%= us.link_to_remove "Remove", class: "btn btn-small red right" %>



Now I don't know how I manage this record in controller for create and update, And also I don't know how will I show this records.... If you understand my problem then pleasr provide me controller code for update and create of resume controller and also help me to show the resume data.

before_filter running out of order

We have following filters in controller:

  before_action :authenticate_api_request!, except: [:reply_messages]
  before_action :community_uuid
  before_action :is_user_blocked?, only: [:create, :like, :dislike, :flag, :reply_message]
  before_action :user_confirmed_email?, only: [:create]
  before_action :get_message, only: [:like, :dislike, :flag, :remove, :get_message_json, :reply_message, :reply_messages]
  before_action :get_reply_message, only: [:reply_message]
  before_action :get_group, only: [:create]
  before_action :is_blocked_from_group?, only: [:create, :like, :dislike, :reply_message]

and order in which they are executed is:

user_confirmed_email?
get_message
get_reply_message
authenticate_api_request!
community_uuid
is_user_blocked?
get_group
is_blocked_from_group?

The problem here is authenticate_api_request!, community_uuid and is_user_blocked? is called after user_confirmed_email?.

Is this a valid call/syntax in ruby?

Is this a valid call/syntax in ruby? ClassA.ClassB.methodOne(param)

Sorry I am new to ruby.

Rails customizing the administrate gem

I have location, concert and artist model as

class Location < ApplicationRecord
  has_many :concerts, dependent: :destroy
  has_many :artists, through: :concerts
end

class Concert < ApplicationRecord
  belongs_to :location
  belongs_to :artist
end

class Location < ApplicationRecord
  has_many :concerts, dependent: :destroy
  has_many :artists, through: :concerts
end

I'am currently using the rails administrate, now I want to customise the rails administrate gem where instead of displaying the id while adding the new concert I want to get the location and artist name there instead of there id's. I have attached the screenshot there.enter image description here

mercredi 21 novembre 2018

SQLite3::BusyException attaching files in seeds.rb

I'm trying to enter data in my seeds file and include attachments as so but it's throwing this error:

SQLite3::BusyException: database is locked

I know the error is the way i'm entering the data and attaching a file but I don't how how else to do multiple records! Help is much appreciated.

This is my seeds file

(v = Apple.create( color: 'Black', size: 'Big', taste: 'bitter;, price: '40,000')
 v.image.attach(io: File.open('app/assets/images/v.jpg'), filename: 'v.jpg'))

(v1 = Apple.create( color: 'Blue', size: 'Big' taste: 'bitter', price: '39,000')
 v1.image.attach(io: File.open('app/assets/images/v1.jpg'), filename:'v1.jpg'))

Upload pdf to amazon in Rails

I have rails app which works with pdf files using PDFKit. I have no problems with

kit = PDFKit.new(data)

kit.to_file("some.pdf")

What I need as result - save my pdf to Amazon S3. How is it possible to save it directly to the S3 or upload it from tmp/ folder (as I'm going to deploy it on Heroku)

calculate time difference in rails postgresql query

I need to get time difference as query result in my rails(which has Postgres database)

Brute Force Approach

I queried all items from my database and then iterating each record and then calculating time difference in hours which is very slow.

1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
2) @image_retouch_items.each do |retouch_item|
      latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
   end

Optimized
I need to calculate the difference of time(hours) in query itself, how to achieve that

like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')

mardi 20 novembre 2018

How to apply where condition to each record

Rails 3.22
I have a table named AccountClose in which i need to display difference of days for each record.
Here is my code

          @a = AccountClose.where("AccountCloseId is not null").last.Date.to_date
          @before = Date.today 
          @difference_in_days = (@before.to_date - @a.to_date).to_i 

Above query only displaying difference_in_days for last record only,I want to display difference_in_days for every HPId which is present in AccountClose
Could anyone help me with this?

How to open a bootstrap modal using rails link_tag and remote: true

I am usinge rails 5.0.2 My view page code is:

 <%= link_to  'Download files',cader_history_path(:job_id => @check_cader[0].job_id), :remote => true, class: "btn btn-link", 'data-toggle' => 'modal', 'data-target' => '#files' %>

But its did not open the modal, after making this call as remote: true Is their any other way round thanks in advance

lundi 19 novembre 2018

How i can write a query inside from in rails

How can I write this query in Ruby on Rails? Query inside a from

select * from (
  select * 
  from points, sports 
  where points.sport_id = sports.id 
  group by sports.id 
  order by max(points.value) desc
) 
order by created_at desc

it's inside a app\models\concerns\scopes\sport.rb, so it should start as

  scope :best_scores_in_sports, lambda {
    joins(:points)
    .select(etc.etc.

...right?

undefined local variable or method `params' for controller

I am trying to implement contact manager with rails. I am using RSpec for test-driven development.

"When I am looking at a single person’s page, I click an add link that takes me to the page where I enter the phone number. I click save, then I see the person and their updated information"

I am trying to validate this action.

In my controller class

describe "POST #create" do
context "with valid params" do
  let(:alice) { Person.create(first_name: 'Alice', last_name: 'Smith') }
  let(:valid_attributes) { {number: '555-1234', person_id: alice.id} }

  it "creates a new PhoneNumber" do
    expect {
      post :create, params: {phone_number: valid_attributes}, session: valid_session
    }.to change(PhoneNumber, :count).by(1)
  end

  it "redirects to the phone number's person" do
    post :create, params: {:phone_number => valid_attributes}, session: valid_session
    @phone_number = PhoneNumber.new(person_id: params[:person_id])
    expect(response).to redirect_to(@phone_number.person)
  end
end

I want to redirect to phone number's person but while getting phone number It gives me an error undefined local variable or method params' for #<RSpec::ExampleGroups::PhoneNumbersController::POSTCreate::WithValidParams:0x00007fc89e276898>

I also have view test as follows

 it 'adds a new phone number' do
  page.click_link('Add phone number')
  page.fill_in('Number', with: '555-8888')
  page.click_button('Create Phone number')
  expect(current_path).to eq(person_path(person))
  expect(page).to have_content('555-8888')
end

Right now this test is also failing because of this error :

expected: "/people/1"
got: "/phone_numbers"

How can I resolve these problems and redirect user as desired? Thanks in advance

dimanche 18 novembre 2018

undefined method 'person' for nil:NilClass

I am trying to create contact manager by following a tutorial. I think that tutorial missing some part and I am stuck while writing tests.

describe "POST #create" do
context "with valid params" do
  it "creates a new PhoneNumber" do
    expect {
      post :create, params: {phone_number: valid_attributes}, session: valid_session
    }.to change(PhoneNumber, :count).by(1)
  end

  it "redirects to the phone number's person" do
    alice = Person.create(first_name: 'Alice', last_name: 'Smith')
    valid_attributes = {number: '555-8888', person_id: alice.id}
    post :create, params: {:phone_number => valid_attributes}, session: valid_session
    expect(response).to redirect_to(@phone_number.person)
  end
 end
end

My code gives the following error

   undefined method `person' for nil: NilClass

As far as I understand, somehow I need to initialize @phone_number. Since I am new to rails I could not figure it out.

Any help would be nice.

Upgrade ruby from ruby-2.0.0-p451 to 2.2.2 on Mac

In our system we are using RoR, when ruby version is ruby-2.0.0-p451 and rails > 3 Our plan is to upgrade rails to 4. When googling for information, we found that it will be smarter to start upgrading ruby first to avoid blocking gem upgrade (so that we will have full support for the rails versions. If we don’t upgrade ruby version, it might block the upgrade of some of the gems needed for rails 4.0 and above.)

So we have decided upgrading Ruby to 2.2.2 first.

Now, I'm trying to understand how can I upgrade to 2.2.2 version by looking for the differences, and map the changes we have to do, but can't find this info. Can someone assist me by pointing me to right location where can I see the features and changes that have to be done in our code? Thanks!

vendredi 16 novembre 2018

Rails, strong parameters, and complex data structures

Good aftern, SO folks

I am strong parameterizing a Rails 3 application that we plan to upgrade to Rails 4. Some of the controllers use the params object to hold not just nested hashes, but hashes within arrays within hashes within arrays etc. Changing the nature of the data structure would be too intense, we want to ideally have it return the same data structure, but strong parameterized

Here's an example as JSON:

"my_example" => {
  "options" =>
   [{"id" => "1"
     "name" => "claire"
     "keywords" => 
       ["foo", "bar"]
     },
    {"id" => "2",
      "name" => "marie",
      "keywords => 
        ["baz"]
    }],
    "wut" => "I know, right?"
}

But for added fun, the keywords array can contain any string. Which I've read about and which is tricky and supported in other versions of rails but whatever.

Are there any general rules of thumb about making complex data structures with the strong_parameters gem? I know that Rails 4 and 5 handle this better, but I'm curious.

How to store encrypted data?

I'm new in ruby on rails, and i'm developing and application that will have very sensitive data (api keys from other websites) and i need to store it encrypted in a db but without knowing them anytime. Let me explain myself: -The form ask the user for his api keys -Encrypt them -Store it in the db

The main question is, how i encrypt them in such a way i can use it later (still without knowing them)

Sorry if the question is silly, but i can't find a way to do it, and thanks

jeudi 15 novembre 2018

ruby - help need to convert an array to a specific type of array of arrays, duplicating the keys as [key, value] int he list

I want to convert and array into a specific type of array of arrays.

array = ["Project", "Publication"]

into

array_of_arrays =[["Project", "Project"], ["Publication", "Publication"] ]

The array is not just limited to size two. Its a growing list , so looking for some function to convert it to array_of_arrays.

Appreciate any help.

mercredi 14 novembre 2018

Erro "While executing gem ... (OptionParser::AmbiguousOption) ambiguous option: --no"

I am new to programming and I am really interested in learning ruby on rails. So, i attempted at installing rails on my macbook with the following command: gem install rails --no-ri --no -rdoc

However, I got the following:

Erro "While executing gem ... (OptionParser::AmbiguousOption) ambiguous option: --no"

So, my question is who do i resolve the cause of the error.

Thanks

Unable to save/update the record into db in rails

I am trying the update the record for the columns IsValid and Comments in rails, but doesn't get updated in backend or any error:

Below is my parameters result:

Started PATCH "/metrics/1" for 
Processing by MetricsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"1oC/1UdAaTPUepy1zIjO1x6n67Th/pdcnvYJH95cB63tZts9d135JIK4MzQD2/pdPoRKnUKXIc0ZI9MQZkjfNQ==", 
  "metrics_controller"=>{"IsValid"=>"False", "Comments"=>"1"}, "commit"=>"Save", "id"=>"1"}
  Metric Load (75.1ms)  SELECT  `Threshold`.* FROM `Threshold` WHERE `Threshold`.`ID` = 1 LIMIT 1
Unpermitted parameters: utf8, _method, authenticity_token, metrics_controller, commit, id
   (75.7ms)  BEGIN
   (75.1ms)  COMMIT

enter image description here

update method in controller:

 def update
        @metric = Metric.find(params[:id])
        #if(@metric.update(post_params))
        if(@metric.update_attributes(post_params))
          redirect_to metrics_path
        else
          render 'edit'
        end
      end
       private def post_params
    params.permit(:Metric, :WI, :Value, :UT, :Score, :IsValid, :UserName, :Comments)
  end

If I update post_params method with the below code it is throwing error:

private def post_params
    params.require(:metric).permit(:Metric, :WI, :Value, :UT, :Score, :IsValid, :UserName, :Comments)
  end

mardi 13 novembre 2018

How to show edit button only for a record and save data to database from edit form in rails

I am displaying all the records from db in the form of HTML table along with edit button. On, click of edit button it redirects to edit view which will display the additional columns.

Here, I was showing save button in edit form for all the rows/records. Is there a way to prevent so that I can just show to the one I selected in index form.

Also, after updating the fields how do I save the record and redirect to index view.

Please find the code snippets below:

metrics_controller.rb:

class MetricsController < ApplicationController
  def index
    @metricAll = Metric.all
  end

  def show
    @metric = Metric.find(params[:id])
  end

  def edit
    @metric = Metric.find(params[:id])
    @metricAll = Metric.all
  end

  def create
    @metric = Metric.new(post_params)
    if(@metric.save)
      redirect_to @metric
    else
      render 'new'
    end
  end

  def update
    @metric = Metric.find(params[:id])
    if(@metric.update_attributes(post_params))
      redirect_to @metric
    else
      render 'edit'
    end
  end

  private def post_params
    params.require(:metric).permit(:Metric, :WI, :Value, :UT, :Score, :IsValid, :UserName, :Comments)
  end
end

edit.html.rb:

<%= form_for :metrics_controller, url: metric_path(@metric), method: :patch do |f| %>
  <table id="metrics">
    <thead>
    <tr id="AllMetricColumnNames">
      <th id="Metric"><div>Metric</th>
      <th id="WI">WI</th>
      <th id="Value">Value</th>
      <th id="UT">UT</th>
      <th id="Score">Score</th>
      <th id="IsValid">IsValid</th>
      <th id="UserName">UserName</th>
      <th id="Comments">Comments</th>
      <th id="EditColumn">Edit</th>
    </tr>
    </thead>
    <% @metricAll.each do |data| %>
      <tr id="AllMetricValues">
        <td id="Value"><%= data.Metric %></td>
        <td id="WI"><%= data.WI %></td>
        <td id="Value"><%= data.Value %></td>
        <td id="UT"><%= data.UT %></td>
        <td id="Score"><%= data.Score %></td>
        <td><%= f.select :IsValid, options_for_select(['True', 'False']), :include_blank => true, :class => 'chosen-select', :required => true, value: data.IsValid  %></td>
        <td id="UserName"><%= data.UserName %></td>
        <td id="Comments"><%= f.text_field :Comments, value: data.Comments %></td>
        <td id="SaveButton"><%= f.submit "Save" %></td>
    <% end %>
    </tr>
  </table>
<% end %>

Screenshot: enter image description here

lundi 12 novembre 2018

CSRF protection when migrating from Rails 3 to Rails 4

I am working on migrating a big website package from Ruby 1.9 to Ruby 2.3, and I'm almost done. I've got Rails almost completely moved from 3.2 to 4.2, but I've run into one snag which I cannot figure out, and this project is my first experience with either Ruby or Rails, so I've been picking up the jargon as I go.

When I point my browser to my development server, all my GET requests succeed (200), but all my POST requests fail (500). After some research, I found out about Rails' built-in CSRF protection, and was able to determine that the package I'm working with had this protection in place when it was using Rails 3.2.

With Rails 4.2 in place, the protection seems to be preventing any POST requests from succeeding. After researching it further, I found that Rails 4 encrypts auth cookies before sending them to the web server, whereas Rails 3 did not, and that it's a good practice to use the Rails 3 cookie until all your users are up to Rails 4. I commented out the secret_key_base definition which I'd created as part of the migration and I cleared out my browser cache, so to my understanding, I should now be using the unencrypted Rails 3 cookie.

However, my POST requests still throw 500s. I can't share much code but I've referenced this official guide and I do have this line in my application controller:

protect_from_forgery with: :exception

I've also verified that if I comment out the protection and use:

skip_before_action :verify_authenticity_token

then the POST requests succeed (they are just very insecure).

Most of what I've read seems to indicate that this feature depends on the protect_from_forgery line I showed above, and that's it.

I cannot seem to get these requests to succeed and I wonder if it's just another layer of knowledge I haven't yet picked up. Would very much appreciate any help.

Any example on how to integrate tokbox with ruby on rails

I am developing a simple app using ruby on rails framework. I would like to add a video conference to my app. I tried skype, hangouts...

I recently learned about this client tokbox.

Does anyone know it whether it can be integrated to ruby on rails app?

tubesock gem is not able to listen on the port of sinatra application

I have a sinatra application running on a port 7095.When I have added code mentioned in https://github.com/ngauthier/tubesock#rack and run puma code,tubesock gem does not listen on 7095.

I have used following in config.ru

run Server.new
run Sinatra::Application

When I run following I get the following error

const socket = new WebSocket('ws://dfr101.com:8096');
undefined
VM222:1 WebSocket connection to 'ws://dfr101.com:8096/' failed: Error during WebSocket handshake: Unexpected response code: 404

Thanks

where are rails inbuilt inbuilt and default method written in rails app?

Can any one explain me Where is "NoMethodError" function written in rails app.

Please let me know where can i get all the rails inbuilt method and function list.

vendredi 9 novembre 2018

Split Stack Development Model

I have been working on this ruby on rails application i wanted to separate my FRONT-END from BACK-END.This way both front-end and back-end should not be dependent on each other.Front-end should be more like a component based and independent. Any good detailed suggestion would really be helpful. Thanks in advance

jeudi 8 novembre 2018

Condition operators don't give correct result in my code ruby

I am very very beginner in ruby and I try to develop battleship game in it. In the program I have to write this game in console with entering coordinates of guessing where the game is and I did it. But there are some problems and I added some if elsif else conditions to code to solve them. But these codes don't work. One of them is for entering coordinates out of board, the second one is for not entering any coordinate, and the last one is for bumped coordinate. If these three condition are bypassed the players can enter any coordinate. But when I check these three conditions the result is stupid errors. Can anyone tell me what is the problem with these conditions? Why they don't give suitable result?

#array1 and array2 are not obvious boards of player1 and player2 respectly 
array1 = [ ['*', 'A', 'B', 'C', 'D', 'E'],['1',0, 1, 1, 1, 0], ['2',1, 0, 0, 0, 0], ['3',1, 0, 1, 0, 0], ['4',0, 0, 1, 0, 1], ['5',0, 0, 0, 0, 0] ]
array2 = [ ['*', 'A', 'B', 'C', 'D', 'E'],['1',1, 0, 1, 1, 0], ['2',0, 0, 0, 0, 1], ['3',0, 1, 0, 0, 1], ['4',0, 1, 0, 0, 1], ['5',0, 0, 0, 0, 0] ]

#arr1 and arr2 are obvious boards of player1 and player2 respectly
arr1 = [['*', 'A', 'B', 'C', 'D', 'E'],['1','.','.','.','.','.'],['2','.','.','.','.','.'],['3','.','.','.','.','.'],['4','.','.','.','.','.'],['5','.','.','.','.','.']]
arr2 = [['*', 'A', 'B', 'C', 'D', 'E'],['1', '.','.','.','.','.'],['2', '.','.','.','.','.'],['3', '.','.','.','.','.'],['4', '.','.','.','.','.'],['5', '.','.','.','.','.']]
coor = ['A', 'B', 'C', 'D', 'E']

#board1 and board2 are the final boards of player1 and player2
#this arrays will be seen during game 
#every changes will be seen on these boards
board1 = arr1.map { |x| x.join(' ') }
board2 = arr2.map { |x| x.join(' ') }

#num1 and num2 are the numbers of the parts of ships respectively
num1 = 8
num2 = 8

#count1 and count2 are the numbers of poped ship parts respectively
count1 = 0
count2 = 0

#Starting of the game and the printing the board 
#If we type "start" game will be started
#"Reset" game will be ended
#If we type words except "start" or "reset" program will ask "Do you want to start? (start/reset)" again
while true do
    puts "Welcome to the game!!!"
    puts "Do you want to start? (start/reset):"
    respond = gets.chomp
    if respond == 'start'
        puts "\n"
        puts "Player ONE"
        puts board1
        puts "\n"
        puts "Player TWO"
        puts board2

        while true do
            #Burada while ile player1 in shertleri olacaq 
            while true do 
                puts "\n"
                puts "Turn - Player ONE"
                puts "Enter coordinate: " 
                a = gets.chomp
                a1 = a.split('')
                b = coor.index(a1[0]) +1
                col1 = b
                row1= a1[1].to_i
                if a == '""'
                    puts "You have to enter any coordinate"
                    break
                elsif array1[row1][col1] == 'X' or array1[row1][col1] == '0'
                    puts "You have already bumped this coordinate!"
                elsif col1<1 or col1>5 or row1>5 or row1<1
                    puts "This coordinate is out of board"
                else
                    if array1[row1][col1] == 1
                        count1 = count1 + 1
                        arr1[row1][col1] = "X"
                    elsif array1[row1][col1] == 0
                        arr1[row1][col1] = "0"
                    end
                    board1 = arr1.map { |x| x.join(' ') }        
                    puts "\n"
                    puts "Player ONE"
                    puts board1
                    puts "\n"
                    puts "Player TWO"
                    puts board2

                    if count1 == num1
                        puts "Player ONE won the game!"
                        break
                    end
                end
                break
            end


            while true do 
                #Burada while ile player2 in shertleri olacaq 
                puts "\n"
                puts "Turn - Player TWO"
                puts "Enter coordinate: " 
                c = gets.chomp
                c1 = c.split('')
                d = coor.index(c1[0]) + 1
                col2 = d
                row2= c1[1].to_i
                if c == '""'
                    puts "You have to enter any coordinate"
                    break
                elsif array2[row2][col2] == 'X' or array2[row2][col2] == '0'
                    puts "You have already bumped this coordinate!"
                elsif col2<1 or col2>5 or row2>5 or row2<1
                    puts "This coordinate is out of board"
                else
                    if array2[row2][col2] == 1
                        count2 = count2 + 1
                        arr2[row2][col2] = "X"
                    elsif array2[row2][col2] == 0
                        arr2[row2][col2] = "0"
                    end
                    board2 = arr2.map { |x| x.join(' ') } 
                    puts "Player ONE"
                    puts board1
                    puts "\n"
                    puts "Player TWO"
                    puts board2

                    if count2 == num2
                        puts "Player TWO won the game!"
                        break
                    end
                end
                break
            end
        end

    elsif respond == 'reset'
        puts "You are off the game"
        break
    else
        puts "\n"
        puts "Answer can be only {start} or {reset}"
    end
end

Rails delete all associations on duplicated object

When duplicating an object with object_dup=object.dup all associations are also copied.

object_dup.foos == object.foos

I would like to destroy all duplicated associations on object_dup. It might be easier to just create a new object. But the duplication saves me from property-setting-hell ;) I would like to duplicate/clone only object itself without the associations or delete them all after the creation. Is that possible?

mercredi 7 novembre 2018

How to use ruby rails and node express

I'm doing a school web project and we are required to use omniauth for user authantication. I also want to use Nodejs express as the core/major part of my project. Is it possible to use rails for the auth part only and then use express for the rest? ...and if yes, how?

Where is the scope variable declared in this source code?

I've been looking through the source code for devise, for the life of me can't figure out how the below code block works (full source here)

def mapping
    @mapping ||= begin
        mapping = Devise.mappings[scope]
        raise "Could not find mapping for #{scope}" unless mapping
        mapping
    end
end

I think understand most parts of this code, but cannot find where the scope variable is declared/defined. I have searched to repository (and the repository this inherits from), and looked at the tests available to try and get a better idea of what's going on here, but can not find any mention of a scope variable anywhere. I'm still learning ruby, so am I missing something obvious/a language construct that I'm unaware of at work here?

Problems with a include or if in rails

Im having issues with rails with the code

if @turno.chop == res[:department].to_s 

where turno contains strings like ABC1 and department like ABC, im trying to filter if turno its equal of department but i need reduce the string of turno for that. Every time what i try to do that the code dont finish and stuck in other part of code, when i delete the condition, the code works perfectly but dont do the filter.

i tryid to to do like

if @turno.include?(res[:department].to_s)

But appears the same error.

mardi 6 novembre 2018

Pass newly created object of after_create callback in Rails

Everytime an object has been created i want to enqueue it in a Redis queue to check for certain properties. How can i add the created object directly as a parameter to the callback? Something like? So my redis job would do something like this:

class FurtherProcessCarJob
 #....

 def self.perform(order)
   puts order.id
 end 
end

whereas in the model

after_create Resque.enqueue FurtherProcessCar, #self

It is possible to hook a method to the callback and there look for the car again and the enqueue the object, but is it possible to do it directly?

adding multipe new columns in rails migration using block

Is there any better way to add new columns to rails table than this way

class AddColumnsToUsers < ActiveRecord::Migration[5.1]
  def change
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string
    add_column :users, :contact1, :integer
    add_column :users, :contact2, :integer
    add_column :users, :contact3, :decimal
    add_column :users, :contact4, :integer
    add_column :users, :contact5, :integer
    add_column :users, :contact6, :string
    add_column :users, :contact7, :integer
    add_column :users, :contact8, :integer
    add_column :users, :contact9, :integer
  end
end

Can we use change_table method and write these inside a block? instead of repeating the add_column again and again

Looking for a way to keep a heritage Rails 3.2 app running securely without upgrading

For context - I recently heard a podcast with Eileen Uchitelle where she said that Github had gradually upgraded from Rails 3.2 to 5.1 over the course of the past year or so. While they were using 3.2, they had to patch any known security issues themselves as that version had been EOL'd for quite a while now (ie. at the end of 2015 or so).

My question is, does anybody know if Github open sources these patches for Rails 3.2 at all? I'm basically looking for a way keep a heritage Rails 3.2 app running securely.

I am aware that it is an option to buy this service from a company like railslts but I want to keep that as a last resort for now.

dimanche 4 novembre 2018

How do I specify the stylesheets in my project are compiled/loaded?

I have a file in my folder theme/skins/default.css and I have another file called /style.css. I want the styles from default.css to be added to my application.css after the styles in style.css. Aside from manually copying them, how do I do it? Basically all the stylesheets in my theme/skins/ folder, I would like to be added to my application.css file after my style.css.

In other words, I would like the styles in my theme/skins/default.css to override the files in my style.css where they do exist.

How do I go about doing that within the constraints of the Rails 3.2 asset pipeline?

Edit 1

Note that I tried this:

/*
 *
 *= require_tree .
 *= require "theme/skins/default"
 *= require_self
 */

@import "bootstrap";
@import "font-awesome";

And that doesn't render it in the correct order.

When I do a view source on my page, this is what I see:

<link href="/assets/theme/skins/default.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href="/assets/theme/slick.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href="/assets/theme/style.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href="/assets/application.css?body=1" media="screen" rel="stylesheet" type="text/css" />

samedi 3 novembre 2018

How to strip column values in Active record through loop before saving in rails framework?

I have to remove spaces for every record before saving into the database. I can do that by specifying it for each column, but when there 100 columns in each record, it is a pain and no of lines of code increases enormously.

Need help in changing the code into a loop, but being an amateur in rails I am not able to complete it.

class hello < ActiveRecord::Base

before_validation :remove_spaces  

def remove_spaces
          self.login = self.login.strip if self.login.present?
          self.email = self.email.strip if self.email.present?
          . so on .......

      end

end

jeudi 1 novembre 2018

how do i make pages show by categories (sections)

i am using active admin to create a blog and i created sections which has_many :pages, if i click on the section, it shows me the section mane cause i used `

<%= @section.name %>

, i want when i click on a section, it shows me all the pages in that section

here's my code show.html.erb

<h1><%= @section.name %></h1>

<% @catSections.each do |section| %>
    <p><%= link_to section.name, section_path(section.id) %></p>
<% end %>

admin/section.rb

ActiveAdmin.register Section do
>     permit_params :name
> index do
>     column :id
>     column :name, :sortable => :name
>     actions end
> 
>     form do |f|
>         f.inputs "Details" do
>             f.input :name, :label => "Name"
>             f.actions
>         end
>     end
> 
> end

application_controller.rb

class ApplicationController < ActionController::Base
    before_action :getAsideSection, :getCatSection, :getHeadCarousel
    def hhome

    end

    def getAsideSection
        @asideSections = Page.all
    end

    def getCatSection
        @catSections = Section.all
    end

    def getHeadCarousel
        @headCarousel = Carousel.all
    end
end

admin/page.rb

ActiveAdmin.register Page do
    permit_params :title, :body, :order, :is_published, :section_id, :menu_display

index do
    column :id
    column :title, :sortable => :title
    column :section, :sortable => :section
    column :created_at, :sortable => :created_at
    column :order
    actions
end

    form do |f|
        f.inputs "Details" do
            f.input :title, :label => "Title"
            f.input :section, :label => "Section"
            f.input :body, as: :html_editor, :label => "Body"
            f.input :order, :label => "Order"
            f.input :is_published, :label => "Published"
            f.input :menu_display, :label => "Display in Menu"
            f.actions
        end
    end

end