jeudi 28 février 2019

paperclip retrieves wrong url with wrong hash key

Thanks for attention,

I have paperclip config as below,

url: "/system/#{scoping}:class/:attachment/:id_partition/:hash_key/:style-:fingerprint/:basename.:extension"

When I upload an image on s3 it creates 4 images with different styles: thumb, original, max, and page

When I retrieve image by pic.image.url it gives

system/staging/pics/images/004/029/680/ba8c01bbc1ce88a002d81778dde225682c047bd1_key/original-5cd21536004adf8b7bbd19b7dd87238d/Homepage.jpg" 

This path is correct.

When I retrieve thumb image by pic.image.url(:thumb) it gives this url, which is wrong.

system/staging/pics/images/004/029/680/c6c22691b51cbff3c8e8647da46de1a7303f9cb4_key/thumb-5cd21536004adf8b7bbd19b7dd87238d/Homepage.jpg" 

while original thumb s3 url is

/system/staging/pics/images/004/029/680/d3653379f2a37b18851e72b06789f4245b2fda34_key/thumb-26462d27921069000a17cbb61a664d6b/Homepage.jpg

same issue happening with other styles. The key which is present in wrong thumb url, does not exist on s3.

the whole path until :id_partition, is correct but then from hash key the rest of url coming wrong

How Can I get exact same full url as when someone hit to get my Rails app

I wanna get full URL in my rails app when someone hit to get my app. like. someone hit the URL in browser.

http://localhost:3000/ so I can get this in rails app with the help of request.original_url, and this gives me the correct result.

but when someone hit URL like this http://localhost:3000/#log-25 so request.original_urlthis is not giving me exact url which hit exactly it only return http://localhost:3000/ but I need #log-25 this part also.

so how can I get whole URL exactly as hit on the browser please help me.

mercredi 27 février 2019

Flutter and Backend Ruby on Rails

friend, I'm finalizing my web system with ruby ​​on rails, so I'll start with the development of my application with flutter, please can you tell me what alternatives there are to connect flutter with the back or if you can share referential information with a back end programmed in another language. thank you.

lundi 25 février 2019

Test razorpay payment flow using cypress

I am trying to use cypress[https://github.com/cypress-io/cypress] for testing my Razorpay payment flow in my ROR project.I am able to get fields in iframe,select a bank and click on "Pay rs399 now".On clicking the "Pay now button" a new window opens up which has two options to make the payment successfull OR fail it. Everything till now is already tested in cypress... My question is how do I access the new window opened using cypress and click "success"

paperclip image rotation not working with s3

Thanks for attention,

I am trying to rotate image uploaded on s3 already. Here is what I implemented.

def rotate!(degrees)
  self.rotation += degrees.to_i
  image.reprocess!
  image.save
  save!
end

Problem: when I save the image after rotation it saves in the local path instead of the original s3 image path.

dimanche 24 février 2019

Change Class based on active record db query with link_to in loop in rails?

Requesting expert help.

I have an applications table which has_many metrics At some point of time, metrics will have following kind of records.

{capture_time:"08:00:10.1234",metric_name:"log",metric_value:"OK",application_id:1} {capture_time:"09:00:10.1234",metric_name:"process",metric_value:"KO",application_id:1} {capture_time:"10:00:10.1234",metric_name:"process",metric_value:"OK",application_id:1}

{capture_time:"08:00:10.1234",metric_name:"log",metric_value:"OK",application_id:2} {capture_time:"09:00:10.1234",metric_name:"process",metric_value:"OK",application_id:2} {capture_time:"10:00:10.1234",metric_name:"process",metric_value:"KO",application_id:2}

I have a bigger loop for applications and for each application , I create buttons for each metric for that application

<% applic.metric.uniq{|p|p.metric_name}.each do |m| %>
<%= link_to m.metric_name, metrics_path(m.application_id,metric_name: m.metric_name) , :class=>"btn btn-success",:role=>"button" %>
<% end %>

enter image description here

On clicking any button it shows me records only for that metrics. For e.g. if I click on process, i see all records of that metric, which is 2 records in my case.

enter image description here

So till here its fine. What I am looking help for is two folds:

  1. How to determine latest metrics(based in capture time) for that application that is KO and then use that to change the class in link_to inside the loop. Something like this:
<% applic.metric.uniq{|p|p.metric_name}.each do |m| %>
<%= link_to m.metric_name, metrics_path(m.application_id,metric_name: m.metric_name),:class=>"btn btn-success",:role=>"button" %>    
<% end %>

Class => btn-danger if latest record for this metric was KO else btn-success

  1. Then I would want to use the combined statuses of the Metrices and change the Class for the whole Application1 box. For e.g if anyone of Process, Log, Errorcounts are all green, which means any of the latest matrices of any of 3 category is KO, then the whole Application1 box has class as "btn-danger"

like this:
enter image description here

vendredi 22 février 2019

Rails ActionController::RoutingError (No route matches [PATCH]

I am trying to create a form where the user would select multiple categories and enrol in all of them at once. I am struggling to understand how this should happen using a custom method add_to_list_de_distrib.

<%= form_for @user, url: url_for(:controller => 'welcome', action: 'add_to_list_de_distrib') do |f| %>
<div class="form-inputs">
<%= f.collection_select(:id, @all_list, :id, :name, {}, multiple: true, autofocus: true, placehodler: true, id: "list_type", :html => {required: true}) %>
</div>
<div class="form-actions ">
<hr>
<%= f.submit "Enrol", class: "btn btn-primary" %>
</div>
<% end %>

I manage to display the form with the collection working. But How do I create the method so that when the user click 'Enrol' it create records in a table for each of the collection item. For now when I simply click on the button, i get : ActionController::RoutingError (No route matches [PATCH] "/en/welcome/add_to_list_de_distrib"): In my routes I do have add_to_list_de_distrib_path GET /welcome/add_to_list_de_distrib(.format)

Redirect all HTTP traffic to HTTPS seems to be impossible

I am posting the question because the previous attempts have proved to be futile.

I have a rails server using nginx, and I am trying to redirect all http traffic to https.

Here is my nginx.conf file:

upstream backend {
  server unix:PROJECT_PATH/tmp/thin1.sock;
  server unix:PROJECT_PATH/tmp/thin2.sock;
  server unix:PROJECT_PATH/tmp/thin3.sock;
  server unix:PROJECT_PATH/tmp/thin4.sock;
  server unix:PROJECT_PATH/tmp/thin5.sock;
  server unix:PROJECT_PATH/tmp/thin6.sock;
  server unix:PROJECT_PATH/tmp/thin7.sock;
  server unix:PROJECT_PATH/tmp/thin8.sock;
}  

server {
  listen 80 default_server;
  listen 443 default_server ssl;

  server_name app_name;
  ssl_certificate path_to_certificate_file.crt;
  ssl_certificate_key path_to_certificatefile.key;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

  root PATH_TO_PUBLIC_FOLDER;
  access_log path_to_project/log/access.log;
  error_log path_to_project/log/error.log;
  client_max_body_size 10m;
  large_client_header_buffers 4 16k;

  location /ping {
    echo "pong"
    return 200;
  }

  # Cache static content
  location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|swf|wav)$ {
    expires max;
    log_not_found off;
  }  

  # Status, local only (accessed via ssh+wget)
  location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
  }

  # double slash removal
  set $test_uri $host$request_uri;
  if ($test_uri != $host$uri$is_args$args)  {
    rewrite ^/(.*)$ /$1 break;
  }

  location / {
    if ($http_x_forwarded_proto = 'http') {
      return 301 https://$server_name$request_uri;   
    }
    try_files $uri @proxy;
  }

  location @proxy {    
    proxy_redirect off;  
    # Inform we are on SSL
    proxy_set_header X-Forwarded-Proto https;

    # force timeouts if one of backend is died
    proxy_next_upstream error timeout invalid_header http_502 http_503;

    # Set headers
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    

    proxy_pass http://backend;
  }

  error_page 500 502 503 504 /500.html;
}

The current configuration causes:

400 Bad Request The plain HTTP request was sent to HTTPS port

You may notice the /ping location. That's because I have the servers behind a GCE balancer that performs a health check, and this is THE ONLY one I do not want to redirect. Everything else should be redirected to HTTPS.

Previous attempts:

server {
  listen 80;

  server_name app_name;

  location /ping  {
    echo "pong";
    return 200;
  }

  location / {
    return 301 https://$server_name$request_uri;
  }
}

With the https server part like the current config (with listen 80 default_server commented). This causes a too many redirections error.

I tried to simply redirect ALL traffic to https, including the health check. GCE expects a 200 response and instead it gets a 301, thus marking the machine as unhealthy and rendering the application useless.

I also tried the ssl on; on the https server config, same result (400)

I also tried to toggle the config.force_ssl = true in the rails project to no avail. Every other solution I try fails too.

Did anyone stumble on this also?

jeudi 21 février 2019

How to convert mongodb data encrypted with Gibberish to RbNaCl

I took over a ROR/MongoDB project that is using Gibberish w/ Mongoid::EncryptedFields

Gibberish is outdated and not supported anymore. The entire database data is encrypted with Gibberish using something like the following.

Mongoid::EncryptedFields.cipher_same_salt = GibberishCipher1.new(ENV['MONGODB_SAME_SALT_KEY'], ENV['MONGODB_SALT'])

I am trying to switch to RbNaCl SimpleBox. My question is when I switch to RbNaCl if I try to pull a view it will need to decrypt the data to show the user. How can I get RbNaCl to decrypt the data that was encrypted with Gibberish? Gibberish encrypted it with Salt

@cipher.encrypt(text, salt: @salt)

mercredi 20 février 2019

Ruby Thin Server ActionView::Template Error

I'm currently stumped on an error when pushing my project to a live environment on Amazon Web Services and then accessing the domain.

ActionView::Template::Error (Command 'java -jar /home/ubuntu/.rvm/gems/ruby-2.1.10@silk/gems/yui-compressor-0.12.0/lib/yui/../yuicompressor-2.4.8.jar --type css --charset utf-8 /tmp/yui_compress20190221-3152-1wh64vu' returned non-zero exit status
  (in /home/ubuntu/ssc-staging/app/assets/stylesheets/application.css)):
    7:     %meta{:'http-equiv' => "X-UA-Compatible", :content => "IE=edge,chrome=1"}/
    8:     %meta{:name => 'viewport', :content => 'width=device-width, initial-scale=1.0'}/
    9:     = favicon_helper
    10:     = stylesheet_link_tag 'application', "//ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
    11:     = yield :css
    12:     = javascript_include_tag 'application'
    13:     = yield :js
  app/views/layouts/application.html.haml:10:in `_app_views_layouts_application_html_haml___4483641441858119908_47087558678120'

The above error comes with this page.

enter image description here

The error specifically comes from line 10, being a stylesheet link tag to jquery-ui.css. If I delete this line my project will load albeit without css styling. If I run the project locally it works fine.

I haven't made any changes to the 'application.html.haml' file. If I do a rollback and deploy on previous functioning commits the same error appears even though these versions of the build worked without a hitch.

Ruby web server is Thin working in conjunction with Nginx.

rail-lambda showing TypeError: async_hooks.executionAsyncId is not a function

I am getting the following error while debug code using rail-lambda

  TypeError: async_hooks.executionAsyncId is not a function       
            at init (src/lambda/node_modules/cls-hooked/context.js:291:32)
            at runInitCallback (async_hooks.js:459:5)
            at emitInitS (async_hooks.js:327:7)
            at setupInit (internal/process/next_tick.js:225:7)
            at process.nextTick (internal/process/next_tick.js:247:5)
            at requestFlush (/src/lambda/node_modules/asap/raw.js:95:17)
            at rawAsap (src/lambda/node_modules/asap/raw.js:18:9)

lundi 18 février 2019

I want to upload Video(1GB) with my rails app

I want to upload large size video through my rails app. Please suggest me best approach to achieve this functionality

Thanks

How to show a alert before sending a form in Rails?

Im trying to show a confirmation button before sending a form in ruby on rails.

The problem is that the solution Im using its not working. First, it shows the alert twice, and after pressing the button 2 times, the form is not sent, and nothing happens.

Here is my code

  <%=form_for @transaction, :url => delete_duplicated_items_transactions_path(),:html=>{:class=>"form-horizontal bol-form"} do |f|%>

    <div>
      <script type="text/javascript">
        var checked = false;
        function selectAll(){
          checked = !checked;
          console.log(checked);
          $("input:checkbox").each(function(){
            $(this).attr('checked', checked);
          });
          return false;
        }
      </script>

      <table class="admin-table data-table" id="usertable">
        <thead>
          <tr>
            <th><input type="checkbox" onclick="selectAll()">Select All</a></th>
            <th>Bill of Lading Name</th>
            <th>Product Lot id</th>
          </tr>
        </thead>
        <tbody id="bill_of_ladings_body">
          <% duplicated.each do |element|%>
            <tr id="row_user_<%=element["product_lot"].id%>">
              <td><%= check_box_tag "product_lots[]", "#{element["bill_of_lading"].id.to_s};#{element["product_lot"].id.to_s}" %></td>
              <td><%=link_to element["bill_of_lading"].name,edit_bill_of_lading_path(:id => element["bill_of_lading"].id)%></td>
              <td><%= element["product_lot"].id %></td>
            </tr>
          <%end%>
        </tbody>
      </table>
    </div>
    <div class="admin-table data-table">
      <br>
      <td align="right">
        <%=f.button "Remove from Bill of Ladings", name: "transaction_type",value: 'remove', :class=>"btn btn-info","data-loading-text"=>"Processing..."%>      
        <%=f.button "Remove from Bill of Ladings and Recycle", name: "transaction_type",value: 'remove_and_recycle' , :confirm => 'If you proceed, the system will delete the selected Lot IDs from the selected Bill Of Ladings and will then recyle all Lot IDs added on the previous step. Any Lot ID that is not selected on this list will not be removed from the corresponding Bill of Lading/s and will not be recycled. Are you sure you want to continue?', :class=>"btn btn-danger","data-loading-text"=>"Processing..."%> 
    </div>
    <div class="alert alert-block">
      <h4>Note: Recycle action won't be applied to any item that is not selected above and it will remain linked to the Bill of Lading mentioned on the corresponding row</h4>
    </div>
  <% end %>

What im doing wrong here?

Rails 3.2 javascript partial is not manipulating the html page

On a page there is a form which submit link sends an ajax request to my controller. I want the controller to update the resource and then update the resource on the page. The controller responds in the following way:

def update
  @article = Article.find(params[:id])
  respond_to do |f| 
    f.js {}
  end 
end

which then uses the following partial: (article/update.js.erb)

<%= Rails.logger.info "in the partial"%>
<%= Rails.logger.info @article.title%>
$("#test").append("<h1> Header</h1>")
$("#json-app").append(" hello <%= @article.title %>");
$("#json-app").append("<p> hello</p>");
$("#comments").append("<%= @article.title %>:");
alert("something")
$("#btn").attr('disabled','disabled') 

The ids i am referencing there are present in the calling view within the form

form_for @article ,remote: true, html: {:'data-type' => 'json'}, id: "update_article_form" do |f|
.... 
<div id="comments"> comments </div>
<div id="json-app"> a response would be nice
   <div id="test"> comments</div>
</div> 
.....
<%= f.submit 'Update!', id: "btn", style: 'float: inline-end'%>

But clicking the button has no effect. In the html-inspector i see the payload and the status 200 response. The logs show:

Started PUT "/article/2223355" for 127.0.0.1 at 2019-02-18 18:04:29 +0100
Processing by v1::ArticleController#update as JSON
...
in the partial
big pott
Rendered v1/article/update.js.erb (2.9ms)
Completed 200 OK in 41.7ms (Views: 8.2ms | ActiveRecord: 2.4ms)

But inside the view the jquery calls dont have an effect.

The response payload is:

true
true
$("#test").append("<h1> Header</h1>")   
$("#json-app").append(" hello big pott");
$("#json-app").append("<p> hello</p>");
$("#comments").append("big pott ");
alert("something")
$("#btn").attr('disabled','disabled') 
$("input[type=submit]").attr('disabled','disabled') 

  • The request header "accept" is set to "text/javascript application/json"
  • The response header "content-type" is set to "text/javascript"

I do not understand why nothing is happening on the page? Which part am i missing? Any suggestions welcome

vendredi 15 février 2019

Rspec;How to include params inside the body

Rspec spec fails on the following test case. Can anyone please help me with sending params inside the body?

Test case:

  describe 'POST search' do
    it 'renders search' do
      request.headers['Content-Type'] = 'application/json'
      request.headers['Accept'] = 'application/json'

      post :search, body: {name: {query_type: 'match', value: ['xy']} }.to_json

      expect(response.status).to eq(200)
      expect(response.body.include?('TWEEDLE'))
    end
  end

Controller:

def search
    page_params = pagination_params

    query_hash = QueryPreprocessor.params_to_query_with_types(JSON.parse(request.body.read).deep_symbolize_keys)
    logger.info "query_hash: #{query_hash}"
    es_query_json = Elastic::QueryBuilder.facility_search_v1(query_hash, page_params).to_json
    logger.info "es query: #{es_query_json}"

    facilities = facility_helper.search es_query_json
    json_response build_facilities_response(facilities)
  rescue ApiError => e
    render json: e.response, status: e.status
  end

and these are the params which I want to include inside the body, which is being called in the controller:

def pagination_params
    page_params = {}
    page_params['size_params'] = params[:size] || 50
    page_params['from_params'] = params[:from] || 0
    page_params['sort_params'] = params[:sort]
    page_params['order_params'] = params[:order]
    page_params
  end

Rspec passes, with pagination params included inside the body.

Unable to launch rails due to "'executable-hooks (= 1.6.0)' (Gem::UnsatisfiableDependencyError)"

Have had this error for a couple of weeks now and keep giving up trying to solve it, forget about it and then rediscover it. The cycle of pain has been killing me.

/Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:231:in `search_for': Unable to resolve dependency: user requested 'executable-hooks (= 1.6.0)' (Gem::UnsatisfiableDependencyError)
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:283:in `block in sort_dependencies'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:277:in `each'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:277:in `sort_by'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:277:in `with_index'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:277:in `sort_dependencies'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/delegates/specification_provider.rb:52:in `block in sort_dependencies'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/delegates/specification_provider.rb:69:in `with_no_such_dependency_error_handling'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/delegates/specification_provider.rb:51:in `sort_dependencies'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/resolution.rb:165:in `initial_state'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/resolution.rb:106:in `start_resolution'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/resolution.rb:64:in `resolve'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver/molinillo/lib/molinillo/resolver.rb:42:in `resolve'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/resolver.rb:188:in `resolve'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/request_set.rb:396:in `resolve'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems/request_set.rb:408:in `resolve_current'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems.rb:243:in `finish_resolve'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems.rb:311:in `block in activate_bin_path'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems.rb:309:in `synchronize'
    from /Users/Samudabamu/.rvm/rubies/ruby-2.1.10/lib/ruby/site_ruby/2.1.0/rubygems.rb:309:in `activate_bin_path'
    from /Users/Samudabamu/.rvm/gems/ruby-2.1.10/bin/rails:23:in `<main>'
    from /Users/Samudabamu/.rvm/gems/ruby-2.1.10/bin/ruby_executable_hooks:24:in `eval'
    from /Users/Samudabamu/.rvm/gems/ruby-2.1.10/bin/ruby_executable_hooks:24:in `<main>'

I've tried completely purging ruby version manager(rvm), reinstalling bundler, xcode, openssl amongst other things. Could this potentially be a $PATH problem? Really clutching at straws here.

Thanks for your time.

jeudi 14 février 2019

The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. - recvfrom(2)

i am trying to install sqlite for rubyonrails, i am using git bush, i have installed RailsInstaller, my command is gem install sqlite

The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. - recvfrom(2)

mercredi 13 février 2019

Nested Resources, passing value to inner index only passes value of 1

Im trying to display the list of words per category. Lets say category(1):Fruits has many words: apple(1), banana(2), grapes(3). category(2):Animals has many words: dog(4), cat(5)

In order to know if i passed the correct object i display the id. but it only passes the first object (category 1)

Im using nested resource, i tried the different formats and tried different parameters to pass and only get errors

This is the routes:

    namespace :admin do
       resources :categories do 
       resources :words
      end
    end

<% @categories.each do |category| %>
    <tr class="d-flex">
      <td class="col-2"><%= category.title %></td>
      <td class="col-6"><p id="description"><%= category.description %></p></td>
      <th class="col-1"><center><%= category.words.count %></center></th>
      <td class="col-3">
         <center>
              <%= link_to category.id, admin_category_words_path(category), class: "btn btn-primary btn-sm" %>
         </center>
      </td>
     </tr>
 <% end %>

When i pass admin_category_words_path(category) = the index /admin/category/n/words

the function in wordscontroller

def index 
        @category = Category.find_by(params[:category_id])
        #@words = @category.words.all <--- will display all the words of this category 
end

it displays the corresponding id on the url but when i display the id its still 1

but when i want is to get the correct object.

How to use mysql2 0.3.16 with Ruby 1.9.3? (uninitialized constant Mysql2::Client::SECURE_CONNECTION)

I'm trying to set up my local Dev Environment to match my team's. I can't upgrade Ruby/Rails/Mysql2 (for the time being).

I know my local mysql config is good (enough?) because I can create a new Rails project and run it just fine. I'm getting the same error if I run rake db:create or rails s or even start IRB and run require 'mysql2'.

I've googled the hell out of this. I was initially using MariaDB as my Mysql implementation locally. So I thought that might be screwing with the mysql2 gem. So I ripped out MariaDB and finally got Mysql 5.6 working (another team version we're locked into at the moment). After successfully upgrading to Mysql 5.6, I'm confident that's 100% not the issue.

I would expect if I had the wrong password for it to complain about the config somehow. But it's always the same.

uninitialized constant Mysql2::Client::SECURE_CONNECTION

Ruby (RVM): ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux] Mysql2: 0.3.16

There have been some other version-related struggles, but nothing this strong. Any help would be greatly appreciated. The only thing I've encountered that I haven't actually tried is building the mysql2 gem locally.

I would expect require 'mysql2' to at least load the gem. Rails nor Rake will work with the gem at all. It's almost like it's missing some internal file.

raise ConnectionNotEstablished, "No connection pool with '#{spec_name}' found." unless pool LOCALHOST3000 not working

      def retrieve_connection(spec_name) #:nodoc:
    pool = retrieve_connection_pool(spec_name)
    raise ConnectionNotEstablished, "No connection pool with '#{spec_name}' found." unless pool
    pool.connection
  end

I am working on a web app from scratch and found alots of error in the ruby on rails code is above. I installed all the gems required and install and connected home page in controller and route.rb but i can't find the solution for this problem.

activerecord (5.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:1009:in `retrieve_connection'

activerecord (5.2.2) lib/active_record/connection_handling.rb:118:in retrieve_connection' activerecord (5.2.2) lib/active_record/connection_handling.rb:90:inconnection' activerecord (5.2.2) lib/active_record/migration.rb:554:in call' actionpack (5.2.2) lib/action_dispatch/middleware/callbacks.rb:28:inblock in call' activesupport (5.2.2) lib/active_support/callbacks.rb:98:in run_callbacks' actionpack (5.2.2) lib/action_dispatch/middleware/callbacks.rb:26:incall' actionpack (5.2.2) lib/action_dispatch/middleware/executor.rb:14:in call' actionpack (5.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:61:incall' web-console (3.7.0) lib/web_console/middleware.rb:135:in call_app' web-console (3.7.0) lib/web_console/middleware.rb:30:inblock in call' web-console (3.7.0) lib/web_console/middleware.rb:20:in catch' web-console (3.7.0) lib/web_console/middleware.rb:20:incall' actionpack (5.2.2) lib/action_dispatch/middleware/show_exceptions.rb:33:in call' railties (5.2.2) lib/rails/rack/logger.rb:38:incall_app' railties (5.2.2) lib/rails/rack/logger.rb:26:in block in call' activesupport (5.2.2) lib/active_support/tagged_logging.rb:71:inblock in tagged' activesupport (5.2.2) lib/active_support/tagged_logging.rb:28:in tagged' activesupport (5.2.2) lib/active_support/tagged_logging.rb:71:intagged' railties (5.2.2) lib/rails/rack/logger.rb:26:in call' sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:incall' actionpack (5.2.2) lib/action_dispatch/middleware/remote_ip.rb:81:in call' actionpack (5.2.2) lib/action_dispatch/middleware/request_id.rb:27:incall' rack (2.0.6) lib/rack/method_override.rb:22:in call' rack (2.0.6) lib/rack/runtime.rb:22:incall' activesupport (5.2.2) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in call' actionpack (5.2.2) lib/action_dispatch/middleware/executor.rb:14:incall' actionpack (5.2.2) lib/action_dispatch/middleware/static.rb:127:in call' rack (2.0.6) lib/rack/sendfile.rb:111:incall' railties (5.2.2) lib/rails/engine.rb:524:in call' puma (3.12.0) lib/puma/configuration.rb:225:incall' puma (3.12.0) lib/puma/server.rb:658:in handle_request' puma (3.12.0) lib/puma/server.rb:472:inprocess_client' puma (3.12.0) lib/puma/server.rb:332:in block in run' puma (3.12.0) lib/puma/thread_pool.rb:133:inblock in spawn_thread'

mardi 12 février 2019

Devise - don't want to open reset password page in case of token is invalid

I'm using devise gem.

I don't want to open the Reset password page (received at my email) if the Devise forget_password_token is not valid or already used.

Right now by default, it asks me to add a new password and password confirmation then when I submit, it say's "token has been expired"

I just want to add a concept of expire device reset password link sent at the email.

Please help!

Thanks

Date is supposed to be validating to true but it is not

Rails 3.2

An action in one of my helper methods is failing, and I don't understand why. The code is:

paid_at = Date.strptime(params[:manually_paid_at], "%m-%d-%Y") rescue nil

I captured the value of params[:manually_paid_at], prior to this line of code, as follows:

logger.info("Manually paid at: #{params[:manually_paid_at]}")

and it is:

02/02/2019

As far as I know, this is a valid date. When I check by running a test console session, as follows:

$ rails c test
Loading test environment (Rails 3.2.18)
[1] pry(main)> mydate = "02/02/2019"
=> "02/02/2019"
[2] pry(main)> Date.strptime(mydate, "%m-%d-%Y")
ArgumentError: invalid date
from (pry):2:in `strptime'

What am I doing wrong. This is a valid date.

Parent-child listing of tags in liquid

Hi I'm new to liquid and I'm struggling a lot with showing the corresponding product tags under the collection where they are assigned to. I've managed to show the corresponding tags in the sidebar but only if I paste the second snippet after the first snippet. But somehow I would like to show the tags as childs to the active collection as parent.

I know it must be simple, but I'm stuck in the dark..

In the first snippet near the end I've marked where the second snippet already works outside the <ul> list.



And the second snippet which shows the corresponding tags:

 <ul class="subnav clearfix">
        
  </ul>

vendredi 8 février 2019

Rails: Devise with 2 models, logout logs out both

I am trying to implement a second devise resource of users to my Rails app. Log in works, but currently when logging out in one section, logs out both.

How can I set up my application in order to be able to keep both separated?

routes.rb:

devise_for :users, :path => 'users'
devise_for :admins, :path => 'admins'

application_controller.rb:

private

# Overwriting the sign_out redirect path method
def after_sign_out_path_for(resource_or_scope)
  if resource_or_scope == :user
    collection_path
  elsif resource_or_scope == :admin
    new_admin_session_path
  else
    root_path
  end
end

# Overwriting the sign_in redirect path method
def after_sign_in_path_for(resource)
stored_location_for(resource) ||
  if resource.is_a?(User)
    collection_opac_path
  elsif resource.is_a?(Admin)
    admin_root_path
  else
    super
  end
end

1.html

<%= link_to 'Log out', destroy_admin_session_path, :method => :delete %>

2.html

<%= link_to 'Log out', destroy_user_session_path, :method => :delete %>

LOG upon logging out user:

Started DELETE "/users/sign_out" for 127.0.0.1 at Fri Feb 08 18:28:11 +0100 2019
Processing by Devise::SessionsController#destroy as HTML
  Parameters: {"authenticity_token"=>"somestring"}
  User Load (0.7ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  Admin Load (0.4ms)  SELECT `admins`.* FROM `admins` WHERE `admins`.`id` = 1 LIMIT 1
  SQL (0.1ms)  BEGIN
   (0.4ms)  UPDATE `users` SET `updated_at` = '2019-02-08 17:28:11', `remember_created_at` = NULL WHERE `users`.`id` = 1
   (0.8ms)  COMMIT
  SQL (0.1ms)  BEGIN
   (0.2ms)  UPDATE `admins` SET `remember_created_at` = NULL, `updated_at` = '2019-02-08 17:28:11' WHERE `admins`.`id` = 1
   (0.3ms)  COMMIT
Redirected to http://localhost:3000/collection
Completed 302 Found in 10ms (ActiveRecord: 2.9ms)

Rails: Devise after_sign_in_path for multiple resources routes to root

I am working on a library catalogue app, which authenticates admins and users. Somehow I am unable to set the after_sign_in_path_for, since login routes now to the public root, instead of the root of each namespace.

I had already implemented an admin namespace and admin authentication and everything was working. In order to customize the sign_out path I had added:

# Overwriting the sign_out redirect path method
def after_sign_out_path_for(resource_or_scope)
  if resource_or_scope == :user
    collection_path
  elsif resource_or_scope == :admin
    new_admin_session_path
  else
    root_path
  end
end

I had already included the user scope in this section, even if I had not implement the resource yet. Everything was working.

Now I want to add a user resource and collection namespace where the catalogue is placed. Since I now need to specify the upon sign_in redirect, I completed the application_controller.rb with:

# Overwriting the sign_in redirect path method
def after_sign_in_path_for(resource_or_scope)
  if resource_or_scope == :user
    collection_opac_path
  elsif resource_or_scope == :admin
    admin_root_path
  else
    root_path
  end
end

Somehow I am now redirected to the main root instead of collection_opac_path or admin_root_path. The later was working before defining the after_sign_in_path.

In my route.rb I have the following entries:

devise_for :users
devise_for :admins

namespace :collection do
  match '/',                          :to => 'opac#home'
  match '/opac',                      :to => 'opac#opac', :as => :opac
  root :to => 'opac#home'
end

namespace :admin do
  ...
  root :to => 'pages#pageadmin'
end

root :to => 'pages#manifesto'

rake routes gives:

     collection    /collection(.:format)       collection/opac#home
collection_opac    /collection/opac(.:format)  collection/opac#opac
collection_root    /collection(.:format)       collection/opac#home

     admin_root    /admin(.:format)            admin/pages#pageadmin
           root    /                           pages#manifesto

What am I doing wrong? How can I get this to work?

Thanks in advance!

SMTP not working in production mode rails

I am having trouble sending email from rails app in production mode. This same settings works fine in development mode but in production it used to give me EOF error now its saying "no implicit conversion of Symbol into Integer " in userscontroller line 5. I dont have that problem either when run in dev mode. I have already tried using :sendmail still doesnt work.

class UsersController < ApplicationController
  def create
    user = User.new(user_params)
    redirect_to root_path
    if ContactMeMailer.contact(user.name, user.email, user.message).deliver_now
      flash[:success] = 'Sent Successfully!!'
    else
      flash[:failed] = 'Try Again'
      render :create
    end
  end

  private
  def user_params
    params.require(:user).permit(:name, :email, :message)
  end
end

this is the settings i have in production.rb

this is production rb too.

jeudi 7 février 2019

Why do I keep getting this ActiveRecord::AssociationTypeMismatch error?

I have two models that have a has_many association to the same object. I have a User, an Admin, and Visits.

Users has_many Visits Admins has_many Visits

Every time I create a Visit with a User it works, but when I do it with an Admin it gives me an error ActiveRecord::AssociationTypeMismatch.

The full error is this:User(#70282715553200) expected, got # which is an instance of Admin(#70282709528720)

def create
@visit = @service.visits.new(visit_params)

if user_signed_in?
  @visit.user = current_user
else
  @visit.user = current_admin
end

if @visit.save
  redirect_to service_visits_path(@service)
else
  redirect_to @services
end

end

class Admin < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and 
:omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :visits, dependent: :destroy
  end

==============================

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and 
:omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable

  has_many :visits, dependent: :destroy
 end

==============================

class Visit < ApplicationRecord
  belongs_to :user
  belongs_to :admin
  belongs_to :service
end

Rails fields_for not creating associated record

In my Rails project, I am creating a Tutorial with an associated Video. When I try to submit this form, in my rails console I keep getting a ROLLBACK as shown below. Can anyone explain to my why it won't save to the database?

My form:

<h2>New Tutorial</h2>
<%= form_for [:admin, @tutorial] do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title, class: "block col-4 field" %>
  <%= f.label :description %>
  <%= f.text_area :description, class: "block col-4 field"  %>
  <%= f.label :thumbnail %>
  <%= f.text_field :thumbnail, class: "block col-4 field"  %>

  <h3>Videos</h3>

  <%= f.fields_for :videos do |builder| %>
    <%= builder.label :title %>
    <%= builder.text_field :title, class: "block col-4 field" %>
     <%= builder.label :description %>
    <%= builder.text_field :description, class: "block col-4 field" %>
    <%= builder.label :thumbnail %>
    <%= builder.text_field :thumbnail, class: "block col-4 field" %>
    <%= builder.label :video_id  %>
    <%= builder.text_field :video_id, class: "block col-4 field" %>
     <%= builder.label :position %>
    <%= builder.text_field :position, class: "block col-4 field" %>
  <% end %>

  <%= f.submit "Save", class: "mt2 btn btn-primary mb1 bg-teal"  %>
<% end %>

My controller:

 class Admin::TutorialsController < Admin::BaseController

  def new
    @tutorial = Tutorial.new
    @tutorial.videos.build
  end

  def create
    @tutorial = Tutorial.new(tutorial_params)
    if @tutorial.save
      flash[:success] = "Successfully created tutorial!"
      redirect_to tutorial_path(@tutorial)
    else
      render :new
    end
  end

  def edit
    @tutorial = Tutorial.find(params[:id])
  end

  def update
    tutorial = Tutorial.find(params[:id])
    if tutorial.update(tutorial_params)
      flash[:success] = "#{tutorial.title} tagged!"
    end
    redirect_to edit_admin_tutorial_path(tutorial)
  end

  private
  def tutorial_params
    params.require(:tutorial).permit(:title, :description, :thumbnail, videos_attributes: [:title, :description, :video_id, :thumbnail, :position])
  end
end

My tutorial model:

class Tutorial < ApplicationRecord
  has_many :videos, ->  { order(position: :ASC) }, dependent: :destroy
  acts_as_taggable_on :tags, :tag_list
  accepts_nested_attributes_for :videos

  scope :without_classroom, -> { where(classroom: false) }
end

And my video model:

class Video < ApplicationRecord
  has_many :user_videos
  has_many :users, through: :user_videos
  belongs_to :tutorial

  validates_presence_of :position 
end

And my rails console log:

Started POST "/admin/tutorials" for 127.0.0.1 at 2019-02-07 10:11:18 -0700
Processing by Admin::TutorialsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"mVD5oCSIAtsTZ86ksWFw4DEpSu2YS89333PK19fhGuck7HMuyoNs3eCulOX2SpX/IPvcPdywMxSxNoa9Q0cu9g==", "tutorial"=>{"title"=>"Sweet nothing", "description"=>"I am here", "thumbnail"=>"www.google.com", "videos_attributes"=>{"0"=>{"title"=>"This thing", "description"=>"Here we are", "thumbnail"=>"kldsfjdsk", "video_id"=>"6", "position"=>"7"}}}, "commit"=>"Save"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:8
   (0.2ms)  BEGIN
  ↳ app/controllers/admin/tutorials_controller.rb:10
   (0.2ms)  ROLLBACK
  ↳ app/controllers/admin/tutorials_controller.rb:10
  Rendering admin/tutorials/new.html.erb within layouts/application
  Rendered admin/tutorials/new.html.erb within layouts/application (4.1ms)
  Rendered partials/_nav.html.erb (1.9ms)
Completed 200 OK in 93ms (Views: 28.7ms | ActiveRecord: 13.7ms)

mercredi 6 février 2019

link is not triggering ajax and my pop up window is not showing in rails

Trying to pop up a window in rails application. I used the jquery-rails gem, in link_to if I give show_new_path then it is showing the controller error in show if I pass show_new_path(format: :js), then it shows my modal as embedded code in next tab. I coded the use case in the following way.

  /*new.html.erb*/
    <%= link_to 'Link', teams_show_path, remote:true %>

    /*team_controller*/
    def show
        @user = User.all
        respond_to do |format|
          format.js 
        end
    end

    /*show.js.erb*/
    $("#modal-window").html("<%= escape_javascript(render 'show') %>");
    $("#modal-window").modal();

    /*_show.html.erb*/
    <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
       <h3 id="myModalLabel">Modal header</h3>
     </div>
     <div class="modal-body">
       **here comes whatever you want to show!**
     </div>
     <div class="modal-footer">
       <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
       <button class="btn btn-primary">Save changes</button>
     </div>

I am a beginner in rails please guide me with your valuable suggestions

mardi 5 février 2019

is it possible to remove a script from a existing migration file rails

So the thing is i pulled new changes from git, in this new changes there is a migration file

def change
  add_column :users, :activated_at, :datetime
  User.all.each do |user|
  user.update(activated_at: user.updated_at)
end

now normally if i want to undo a migration ie remove a column say activated_at i have to run another migration to do so which is fine

but if i just want to remove the script ie user.update(activated_at: user.updated_at), do i have to create another migration or do i just remove the script from the migration

note: i dont want to remove the activated_at column, i just want to remove the script

Pop up window in rails is not shown on clicking of a button

I am working in an application where on clicking a button I should pop up a small window with a drop-down list of users. on-licking any one of those users, I should get user_id and it should be saved in one more model

my team controllers view has

new.html.erb // contains my form code

_new.html.erb // contains modal code

new.js.erb //contains js code

implemented in the following way

//controller

  def new
        @team=Team.new

        respond_to do |format|
          format.html
          format.js
        end

      end

//_new.js.erb

$("#modal-window").find(".modal-content").html("<%= j (render 'new') %>");
$("#modal-window").modal();

//new.html.erb

    <%= form_for :team, :html => { :class => "form-horizontal team" } do |f| %>

        <div class="col-md-6 col-md-offset-3">
        <div class="form-group">
          <%= f.label :team_name, :class => 'control-label col-lg-2' %>
          <div class="col-lg-10">
            <%= f.text_field :team_name, :class => 'form-control' %>
          </div>
        </div>

    <%= link_to 'Select Captain', teams_new_path,  {:remote => true, 'data-toggle' =>  "modal", 'data-target' => '#modal-window', class: 'btn btn-primary btn-lg'}  %>
    <div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
       <div class="modal-content"></div>
      </div>
    </div>

        <div class="form-group">
          <%= f.label :ground_name, :class => 'control-label col-lg-2' %>
          <div class="col-lg-10">
            <%= f.text_field :ground_name, :class => 'form-control' %>
          </div>
        </div>

        <div class="form-group">
          <div class="col-lg-offset-2 col-lg-10">
            <%= f.submit nil, :class => 'btn btn-primary' %>
            <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                      teams_new_path, :class => 'btn btn-default' %>
          </div>
        </div>
        </div>
      <% end %>

//_new.html.erb

    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">x</button>
      <h4 class="modal-title" id="myModalLabel">Modal title</h4>
    </div>
    <div class="modal-body">
    <%= select(:user_id, User.all.map{|e| [e.full_name, e.id]},{ include_blank: "Please select"}, multiple: true ) %>
    </div>
    <div class="modal-footer">
      <button class="btn btn-primary">Save</button>
    </div>

now its displaying my new.html.erb but no actions are undertaken

//log shows

Started GET "/teams/new" for 127.0.0.1 at 2019-02-06 10:24:52 +0530
Processing by TeamsController#new as JS
  Rendering teams/new.js.erb
  Rendered teams/_new.html.erb (0.3ms)
  Rendered teams/new.js.erb (1.8ms)
Completed 200 OK in 9ms (Views: 6.5ms | ActiveRecord: 0.0ms)

pop up window is not showing please help me with correct guidance

How to consume Multipart/form-data via Ruby Controllers?

I know I'm receiving a file with Content-Type: multipart/form-data in my controller and I understand the file was uploaded with something like this:

body[:uploaded_data] = Faraday::UploadIO.new(path, mime_type, hash[:filename])

and the content of the file I receive is like this

    -------------RubyMultipartPost
Content-Disposition: form-data; name="filename"

1_BsKbDTA9ZUVroeJ7asId4Q.png
-------------RubyMultipartPost
Content-Disposition: form-data; name="uploaded_data"; filename="RackMultipart20190205-12268-1eli4dv"
Content-Length: 34441
Content-Type: image/png
Content-Transfer-Encoding: binary

‰PNG


 IHDR
awùé¨gP\ÆñÇèŒÎÌ_ý....

I'm trying to parse this so that I only get the content of the png file and save it as an actual png file.

I started by making a mock Rack env and parse it

env = Rack::MockRequest.env_for(
        '/',
        'CONTENT_TYPE' => request.headers['Content-Type'],
        'CONTENT_LENGTH' => request.body.length,
        'rack.input' => StringIO.new(request.body.read),
    )
    parsed_message = Rack::Multipart.parse_multipart(env)

and I know parsed_message['uploaded_data'] has the second part but I still don't know how to properly parse out the 4 lines that include Content-Disposition, Content-Length, Content-Type, Content-Transfer-Encoding and get only the file content.

Any ideas are appreciated!

Ruby can't loading the 'sqlite3'

~/my_first_rails_app$ rails generate scaffold car make:string model:string year:integer /home/othmane/.rbenv/versions/2.6.0/lib/ruby/2.6.0/bundler/rubygems_integration.rb:408:in `block (2 levels) in replace_gem': Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? can't activate sqlite3 (~> 1.3.6), already activated sqlite3-1.4.0. Make sure all dependencies are added to Gemfile. (LoadError)

lundi 4 février 2019

can't activate sqlite3 (~> 1.3.6), already activated sqlite3-1.4.0

I’m using Ubuntu and run into to a problem when using db:migrate for ruby project.

rails aborted! LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? can't activate sqlite3 (~> 1.3.6), already activated sqlite3-1.4.0. Make sure all dependencies are added to Gemfile. /home/juan/odin_on_rails/RailsaAPP/bin/rails:9:in <top (required)>' /home/juan/odin_on_rails/RailsaAPP/bin/spring:15:in' bin/rails:3:in load' bin/rails:3:in'

Caused by: Gem::LoadError: can't activate sqlite3 (~> 1.3.6), already activated sqlite3-1.4.0. Make sure all dependencies are added to Gemfile. /home/juan/odin_on_rails/RailsaAPP/bin/rails:9:in <top (required)>' /home/juan/odin_on_rails/RailsaAPP/bin/spring:15:in' bin/rails:3:in load' bin/rails:3:in' Tasks: TOP => db:migrate => db:load_config (See full trace by running task with --trace)

I have created a table in rails using the migration file. But I am not able to access the table in the rails console

I have created a table called as Flowlogs in the rails application using the migration file. I've also fed the data to that table in the rails console. All of a sudden when I try to manually feed the data in the rails console then I get the error.

I've created a table named "flowlogs" and there are two columns in the table with the names vpc_id and flowlog_id. I've logged into the rails console and gave a=Flowlogs.new() and then a.vpc_id="1234" and a.flowlog_id="a1234" and finally gave a.save. This has successfully worked and I have cross-checked using by using the command Flowlogs.all. It has shown the output. But after sometime when I logged into the console and gave Flowlogs.all, then it kept throwing the errors.

Most importantly when I logged into the mysql console and checked there is table with the data with I fed manually in the rails console

My database name is fusion.

Flowlog Load (1.4ms)  SELECT `flowlog`.* FROM `flowlog`
Hirb Error: Mysql2::Error: Table 'fusion.flowlog' doesn't exist: SELECT `flowlog`.* FROM `flowlog`
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:120:in `_query'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:120:in `block in query'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:119:in `handle_interrupt'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:119:in `query'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in `block in execute'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract_adapter.rb:472:in `block in log'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract_adapter.rb:466:in `log'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in `execute'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in `execute'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/mysql2_adapter.rb:235:in `exec_query'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:356:in `select'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:32:in `select_all'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/query_cache.rb:70:in `select_all'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/querying.rb:39:in `find_by_sql'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/relation.rb:639:in `exec_queries'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/relation.rb:515:in `load'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/relation.rb:243:in `to_a'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activerecord-4.2.6/lib/active_record/relation/delegation.rb:46:in `to_ary'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/formatter.rb:88:in `Array'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/formatter.rb:88:in `determine_output_class'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/formatter.rb:53:in `format_output'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/view.rb:205:in `render_output'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/view.rb:123:in `view_output'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/view.rb:201:in `view_or_page_output'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/hirb-0.7.3/lib/hirb/view.rb:187:in `output_value'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:490:in `block (2 levels) in eval_input'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:623:in `signal_status'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:486:in `block in eval_input'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb/ruby-lex.rb:246:in `block (2 levels) in each_top_level_statement'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb/ruby-lex.rb:232:in `loop'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb/ruby-lex.rb:232:in `block in each_top_level_statement'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb/ruby-lex.rb:231:in `catch'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb/ruby-lex.rb:231:in `each_top_level_statement'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:485:in `eval_input'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:395:in `block in start'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:394:in `catch'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/irb.rb:394:in `start'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'
    /Users/masettya/fusion_app/bin/rails:9:in `<top (required)>'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
    /Users/masettya/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    /Users/masettya/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    -e:1:in `<main>'

This is my migration file

class CreateFlowlogs < ActiveRecord::Migration
  def change
    create_table :flowlogs do |t|
        t.string :account_name
        t.string :region
        t.string :vpc_id
        t.string :flowlog_id
        t.boolean :status
    end
  end
end

Rails CanCanCan resource abilities based on department

I have two user types Admin and Normal User

I have the following departments

  • Front Office (eg., id is 1)
  • Back Office (eg., id is 2)
  • Admin (eg., id is 3)

I have a model named Entry which takes user_id, department_id, customer_id

Admin user has full control CRUD over all departments and all entries

Normal User are created for respective department and has CRU control over entries of respective department

When I create an entry from Normal User (eg., id is 2) account I get the correct set of customer_id, department_id, user_id in the table. The ability of this user has only one entry can_create_entry(current_user.id, customer_id, department_id) eg., (1, 1, 2) for front office normal user account.

When I create an entry from Admin(eg., id is 1) account, I get the customer_id, department_id, user_id as (1,1,1) in the table wen i tried to create an entry for Back office department whose id is 2.

When I examined the Ability list for Admin user; I found there is a duplicate for entries ability viz.,

#<CanCan::Rule:0x0000000b61fd18 @match_all=false, @base_behavior=true, @actions=[:create], @subjects=[Entry(Table doesn't exist)], @conditions={:user_id=>1, :customer_id=>2, :department_id=>1}, @block=nil>

#<CanCan::Rule:0x0000000b61fd18 @match_all=false, @base_behavior=true, @actions=[:create], @subjects=[Entry(Table doesn't exist)], @conditions={:user_id=>1, :customer_id=>2, :department_id=>2}, @block=nil>

#<CanCan::Rule:0x0000000b61fd18 @match_all=false, @base_behavior=true, @actions=[:create], @subjects=[Entry(Table doesn't exist)], @conditions={:user_id=>1, :customer_id=>2, :department_id=>3}, @block=nil>

And for Normal User I have only one entry

#<CanCan::Rule:0x0000000b61fd18 @match_all=false, @base_behavior=true, @actions=[:create], @subjects=[Entry(Table doesn't exist)], @conditions={:user_id=>2, :customer_id=>2, :department_id=>1}, @block=nil>

Kindly help me fix the issue for admin role.

samedi 2 février 2019

How to put in some data before my rspec test

Im testing a create method on my controller. The creation of the new entity requires another entity already exist in the database. So i need the foreign key before I can insert anything. I have tried

job = Job.create(:client_id => 1, :title => "Title", :date => Time.now, 
   :number_of_workers => 10, :venue => "Somewhere")

  let(:valid_attributes) {
    {
      worker_id: 1,
      job_id: 1,
      salary: 120.0
    }
  }

  let(:valid_session) { {} }

  describe "GET index" do
    it "assigns all hours ad @hours" do
      hour = Hour.create! valid_attributes
      get :index, {}, valid_session
      expect(assigns(:hours)).to eq([hour])
    end
  end

This works but it breaks another test since my Jobs table is now populated. How can I can I create this job in only this test? (I looked at database_cleaner gem but I like to avoid that)

I tried moving the creation of the job into the for each group but then the variable is not accessible.