mardi 5 février 2019

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.