Sunday, August 14, 2016

dealing with #create as json with Rails 4, dropzone.js, carrierwave | Fixed issues

dealing with #create as json with Rails 4, dropzone.js, carrierwave | Fixed issues


dealing with #create as json with Rails 4, dropzone.js, carrierwave

Posted: 14 Aug 2016 07:40 AM PDT

Using dropzone.js

Started POST "/photos"  Processing by PhotosController#create as JSON  Parameters: {"utf8"=>"✓", "authenticity_token"=>"4ZYgROGmbmA7znV9JAG7rfzVhDLfcaDoAVHVJtvj0Il5EEgBDaPCBk99HLaVKxfl69o+cs/aZgpch2Hj5kR7dw==", "photo"=>{"user_id"=>"2"}, "file"=>#<ActionDispatch::Http::UploadedFile:0x007fd784bb2ef8 @tempfile=#<Tempfile:/tmp/RackMultipart20160814-13-1roacdt.JPG>, @original_filename="DSCN2462.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"DSCN2462.JPG\"\r\nContent-Type: image/jpeg\r\n">}  [1mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1[0m  [["id", 2]]  [1mROLLBACK[0m  Rendered photos/create.json.erb (0.0ms)    def create    @photo = current_user.photos.build(photo_params)  end    <%= form_for :photo, url: photos_path, html: {class: 'dropzone', id: 'dropform' } do |f| %>    <%= f.hidden_field :user_id, value: current_user.id %>  <% end %>    <script type="text/javascript">    $(document).ready(function(){      Dropzone.autoDiscover = false;      $("#dropform").dropzone({          maxFilesize: 5,          paramName: "photo[picture]",          addRemoveLinks: false,       });   });  </script>  

When a photo is added to the dropzone, there is a checkmark on it but it is not being entered into the database. There is no commit. There was an error before:

ActionView::MissingTemplate - Missing template items/continue, application/continue with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :arb, :haml, :jbuilder]}.

so I made a create.json.erb file but I do not know what to put into it.

Also, to get to this point, I had to remove some validations from photo.rb because I was getting error messages like include?... I guess because data was being sent in json it couldn't read the validations.

Rails postgres function in seed file

Posted: 14 Aug 2016 06:59 AM PDT

I have a few postgres functions in my database but when I switched over to using a docker container the functions dont get added into my database because the schema doesnt store functions in it. If I just add it in a migration file (which Ive done) I have to make a new migration if I need to clear the database and rebuild it. I currently use a seed file to put data in. Is there a way to add a function through the seed file so I can call that to make sure the functions are in the database?

Fix 2 user performing same action at the same time

Posted: 14 Aug 2016 06:37 AM PDT

I'm running into a scalability issue where a User can connect to a store. However that store can only be connect to one User.

The issue now is that multiple User are clicking "connect" at the exact same time, and that messes it up.

I put it in a background job that runs this with Sidekiq:

ActiveRecord::Base.connection_pool.with_connection do    store = Store.find_by(guid: guid)    return unless store    store.connect!  end  

I thought that this would solve the issue of never allowing 2 of these actions to be performed at the same time, I guess they should be queued in a way.

How can I fix this?

Rails login test - Fixtures not updated?

Posted: 14 Aug 2016 05:49 AM PDT

In my application user after logging arrives +1 experience. I am trying to write a test that checks whether the experience certainly has been added.

User model:

def add_experience(how)      update_attribute(:experience, experience + how)   end  

Session helper:

def log_in(user)      session[:user_id] = user.id      user.add_experience(1)   end  

and Session Controller

def create      user = User.find_by(email: params[:session][:email].downcase)      if user && user.authenticate(params[:session][:password])        flash[:success] = "Success!"        log_in user        params[:session][:remember_me] == '1' ? remember(user) : forget(user)        redirect_to root_path      else        flash.now[:danger] = 'Ups!'         render 'static_pages/home'      end    end  

After logging in actually adds experience points, but test out the error:

"@user.experience" didn't change by 1.  Expected: 1    Actual: 0  

Test login:

def setup      @user = users(:example)   end    test "example login test" do      get root_path      assert_difference '@user.experience', 1 do      post login_path, params: { session: { email:    @user.email,                                            password: 'password' } }      end  end  

Fixtures:

example:    name: Example name    email: ex@example.com    password_digest: <%= User.digest('password') %>    experience: 0  

Rails how to route to destroy from a different controller action

Posted: 14 Aug 2016 04:44 AM PDT

Before a user deletes their account I want them to submit a form. I would like this to happen with one button click. In my case the destroy action is in the registrations_controller (using devise).

delete_form_controller

  def create      @delete_form = DeleteForm.new(params[:delete_form])      @delete_form.request = request      if @delete_form.deliver        # what code goes here?      else        redirect_to :back      end    end  

As far as I understand you can't redirect with a delete method.

How can I submit the form and delete the user account in one click?

rails 5 turbolinks 5 and google maps how to?

Posted: 14 Aug 2016 03:23 AM PDT

I'm using rails 5 with turbolinks 5 and trying to get google places autocomplete address form to work using the example from google's website found here

I only want to load the javascript and google maps library on this page.

What would be the correct way to get the following javascript to work with rails 5 and turbolinks 5.

<script>    // This example displays an address form, using the autocomplete feature    // of the Google Places API to help users fill in the information.      // This example requires the Places library. Include the libraries=places    // parameter when you first load the API. For example:    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">      var placeSearch, autocomplete;    var componentForm = {      street_number: 'short_name',      route: 'long_name',      locality: 'long_name',      administrative_area_level_1: 'short_name',      country: 'long_name',      postal_code: 'short_name'    };      function initAutocomplete() {      // Create the autocomplete object, restricting the search to geographical      // location types.      autocomplete = new google.maps.places.Autocomplete(          /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),          {types: ['geocode']});        // When the user selects an address from the dropdown, populate the address      // fields in the form.      autocomplete.addListener('place_changed', fillInAddress);    }      function fillInAddress() {      // Get the place details from the autocomplete object.      var place = autocomplete.getPlace();        for (var component in componentForm) {        document.getElementById(component).value = '';        document.getElementById(component).disabled = false;      }        // Get each component of the address from the place details      // and fill the corresponding field on the form.      for (var i = 0; i < place.address_components.length; i++) {        var addressType = place.address_components[i].types[0];        if (componentForm[addressType]) {          var val = place.address_components[i][componentForm[addressType]];          document.getElementById(addressType).value = val;        }      }    }      // Bias the autocomplete object to the user's geographical location,    // as supplied by the browser's 'navigator.geolocation' object.    function geolocate() {      if (navigator.geolocation) {        navigator.geolocation.getCurrentPosition(function(position) {          var geolocation = {            lat: position.coords.latitude,            lng: position.coords.longitude          };          var circle = new google.maps.Circle({            center: geolocation,            radius: position.coords.accuracy          });          autocomplete.setBounds(circle.getBounds());        });      }    }  </script>    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"      async defer></script>  

Using Maps JavaScript API with response from Google Maps Directions API

Posted: 14 Aug 2016 03:37 AM PDT

I'm trying to use Maps JavaScript API with response from Google Maps Directions API to display driving routes passing some waypoints.

I wrote this code below to get waypoints' order using Google Maps Directions API, which is working well.

google_directions.rb

def initialize(origin, destination, waypoints, opts=@@default_options)        @origin = origin        @destination = destination        @waypoints = 'optimize:true' + waypoints        @options = opts.merge({:origin => @origin, :destination => @destination, :waypoints => @waypoints})      @url = @@base_url + '?' + @options.to_query + '&key=' + Rails.application.secrets.google_maps_api_key      @response = open(@url).read    @jdata = JSON.parse(@response)    @status = @jdata['status']  end    def public_response      @response  end  

Now, I get json response(@response) from Google Maps Directions API, so I want to reuse it to display the routes on the google map with Maps JavaScript API.

index.html.erb

<script type="text/javascript">      handler = Gmaps.build('Google');    handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){      markers = handler.addMarkers(<%=raw @hash.to_json %>);      handler.bounds.extendWith(markers);      handler.fitMapToBounds();      toRender(<%=raw @response.to_json %>)    });    function toRender(response){      directionsDisplay = new google.maps.DirectionsRenderer();      directionsDisplay.setDirections(response);    }  </script>  

I'm gessing I should pass @response to directionsDisplay.setDirections() as an argument, but it's not working. Could anyone show me the best way to solve this??

I found this Q&A, which says I need to translate the JavaScript API JSON response into a DirectionsResult object. Does anyone know how to do it??

Displaying results of google direction web service without using javascript api

Param is missing in rspec test

Posted: 14 Aug 2016 04:58 AM PDT

I have the following RSpec test defined:

test 'invalid signup information' do      get signup_path      assert_no_difference 'User.count' do          post users_path, params: { user: { name:  '',                                             email: 'user@invalid',                                             password:              'foo',                                             password_confirmation: 'bar' } }      end      assert_template 'users/new'  end  

And the following Controller:

class UsersController < ApplicationController      def new      @user = User.new    end      def create      @user = User.new(user_params)      if @user.save        redirect_to new_user_path      else        render :new      end    end      def show      @user = User.find(params[:id])    end      private      def user_params      params.require(:user).permit(:name, :email, :password, :password_confirmation)    end  end  

If I execute rake test I get the following error:

ERROR["test_invalid_signup_information", UserSignupTest, 0.35556070700022246]   test_invalid_signup_information#UserSignupTest (0.36s)  ActionController::ParameterMissing:         ActionController::ParameterMissing: param is missing or the value is empty: user              app/controllers/users_controller.rb:23:in `user_params'              app/controllers/users_controller.rb:8:in `create'              test/integration/user_signup_test.rb:7:in `block (2 levels) in <class:UserSignupTest>'              test/integration/user_signup_test.rb:6:in `block in <class:UserSignupTest>'  

The test runs without problems if i delete the require statement in user_params. But I do send a user - So why does it fail?

SLIM add space at start of multi line

Posted: 14 Aug 2016 06:58 AM PDT

I am trying to add a space to the start of my slim template where I have had to break the text due to a link, I cant for the life of me work this one out

.mdl-cell.mdl-cell--4-col-phone.mdl-cell--8-col-tablet.mdl-cell--12-col-desktop    | Don't have an account?    = link_to 'Create one here.', sign_up_path  

Carrierwave, save record?

Posted: 14 Aug 2016 07:17 AM PDT

Hello I am following carrierwave documentation but where do I have to put this part ?

u = User.new(params[:user])  u.save!  u.avatars[0].url # => '/url/to/file.png'  u.avatars[0].current_path # => 'path/to/file.png'  u.avatars[0].identifier # => 'file.png'  

EDIT

Hello thanks for your help !

In this controller I already have a create method I am using it for the admin to post some kind of articles... I wanna add the multiple images

here is my method:

def create  respond_to do |format|    if  @progress.save!        format.html { redirect_to @progress, notice: 'progress was successfully created.' }        format.json { render :show, status: :created, location: @progress }    else      format.html { render :new }      format.json { render json: @progress.errors, status: :unprocessable_entity }    end  end  

end

How do I add the first snippet ?

it should looks more like this then:

  pr = Progress.new(params[:progress])    pr.save!    pr.images[0].url # => '/url/to/file.png'    pr.images[0].current_path # => 'path/to/file.png'    pr.images[0].identifier # => 'file.png'  

thanks again :)

Rails Active admin two index pages conflict

Posted: 14 Aug 2016 02:16 AM PDT

I am building a rails by active admin, the situation is:
Three Resources: order, material , supplier Relationship is:
one order has_many materials
one supplier has_many materials

I want to have two index pages for order_materials and supplier_materials, so that then I click on an order item, the index page will display all related materials,and the same for suppliers.

I hope two pages have path like below
one path is:
admin_order_materials GET /admin/orders/:order_id/materials(.:format) admin/materials#index

the other path is:
admin_supplier_materials GET /admin/suppliers/:supplier_id/materials(.:format) admin/materials#index

I added material resource in order.rb like this, it works well

ActiveAdmin.register Material do      belongs_to :order   end

l do belongs_to :order end

But when I put the same code in supplier.rb, the first path for order_materials disappeared.

ActiveAdmin.register Material do  	belongs_to :supplier  end

I don't why I can not have two material index pages. Any body could help this? Thanks in advance.

Update devise user attributes as nested attributes from another controller

Posted: 14 Aug 2016 01:03 AM PDT

I have user model, and each user has_one profile model. I want to update profile model. But there just two attributes in User model (first_name, and last_name). So I used accepts_nested_attributes_for.

When I call update action, I receive the following errors on profile model:

  1. email can't be blank
  2. password can't be blank

The following my code:

User Model:

class User < ActiveRecord::Base      devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable,       :confirmable     has_one :profile  end  

Profile Model:

class Profile < ActiveRecord::Base   belongs_to :user   accepts_nested_attributes_for :user  end  

Profile controller - update action

class ProfilesController < ApplicationController     def profile_params        params.require(:profile).permit(:current_city_id, :current_country_id, :google_plus_page_url, :linkedin_page_url, :facebook_page_url, :skype_id, :user_attributes => [:first_name, :last_name])    end    def update       @profile = Profile.find_by_id(params[:profile_id])       respond_to do |format|         if @profile.update(profile_params)            format.json { render :show, status: :ok, location: @profile }         else            format.json { render json: @profile.errors, status: :unprocessable_entity }         end       end    end  end  

So, How can I update profile with user's nested attributes without email & password (In Profile Controller Not in devise controller) ??

Devise's edit user page doesn't want to save a text area I've added

Posted: 14 Aug 2016 12:03 AM PDT

As the title says, I've added a text area to devise's edit page, but whenever I click Update, it doesn't update it, it just stays blank all the time.

Here's my edit view:

<h2>Edit <%= resource_name.to_s.humanize %></h2>    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>    <%= devise_error_messages! %>      <div class="field">      <%= f.label :current_goals %><br />      <%= f.text_area :current_goals, autocomplete: "off" %>    </div>      <div class="field">      <%= f.label :email %><br />      <%= f.email_field :email, autofocus: true %>    </div>      <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>      <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>    <% end %>      <div class="field">      <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />      <%= f.password_field :password, autocomplete: "off" %>      <% if @minimum_password_length %>        <br />        <em><%= @minimum_password_length %> characters minimum</em>      <% end %>    </div>      <div class="field">      <%= f.label :password_confirmation %><br />      <%= f.password_field :password_confirmation, autocomplete: "off" %>    </div>      <div class="field">      <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />      <%= f.password_field :current_password, autocomplete: "off" %>    </div>      <div class="actions">      <%= f.submit "Update" %>    </div>  <% end %>    <h3>Cancel my account</h3>    <p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>    <%= link_to "Back", :back %>  

application_controller:

def configure_permitted_parameters    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:other_attributes, :current_goals) }  end  

However, if I don't define a method called current_goals in my user.rb, rails will give me an error, undefined method current_goals.

user.rb

def current_goals  end  

How do I make it save the information I give it?

Rails 4 - Simple Form - how to get rid of the label

Posted: 13 Aug 2016 11:58 PM PDT

I'm trying to figure out how to use simple form without the pre-determined label.

I've tried setting label to false as set out below, but it doesn't stop the label of the attribute ('trl') from appearing beside the collection.

<%= f.input :trl do %>      <%= f.select :trl, Trl.all.map { |t| [t.title, t.id] }, label: false,  include_blank: false, prompt: 'Select one' %>      <% end %>  

Is there a way to dis-apply the labels in simple form?

Why do Carrierwave and asset pipeline appear to interpret config.asset_host differently?

Posted: 14 Aug 2016 01:15 AM PDT

This issue occurs in a Prawn PDF generator in my Rails app, where I have the following line:

image open(@user.avatar.url)  

In tests this line began failing with the following error:

No such file or directory @ rb_sysopen - /images/fallback/default.png  

Avatar is a Carrierwave uploader, with a default image (see here)

def default_url(*args)    ActionController::Base.helpers.asset_path("images/fallback/default.png" )  end  

This seemed like it would be an easy fix — define the asset host in test.rb

config.asset_host = Rails.root.join('app', 'assets').to_s  

but then all my JS enabled feature tests began failing

Capybara::Poltergeist::JavascriptError:  One or more errors were raised in the Javascript code on the page.  ReferenceError: Can't find variable: SomeVariable  

because the paths are being constructed with two assets, e.g.

...app/assets/assets/jquery..

I am clearly doing something "unconventional" that goes against the Rails way of doing things. So I'm wondering what the convention is here.

One solution would be to move where I'm defining the asset folder from test.rb to the uploader.

#config/environments/test.rb  config.asset_host = Rails.root.join('app').to_s  #app/uploaders/avatar.eb  def default_url(*args)    ActionController::Base.helpers.asset_path("assets/images/fallback/default.png" )  end  

but this would mean that helpers.asset_path is not in fact calling the asset path but the app folder, which again seems to go against Rails convention.

I had thought the localhost would work

config.asset_host = "http://localhost"  

but again JS files are failing

I'm sure I'm overlooking something obvious here. Grateful for pointers in the right direction.

Unable to install capybara-webkit even though qt is installed

Posted: 13 Aug 2016 11:22 PM PDT

I want to install gem capybara-webkit but when I run bundle install, I get the following errors:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.    /home/dineshp/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20160814-4696-3d7ixk.rb extconf.rb   *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may need configuration options.    Provided configuration options:  --with-opt-dir  --without-opt-dir  --with-opt-include  --without-opt-include=${opt-dir}/include  --with-opt-lib  --without-opt-lib=${opt-dir}/lib  --with-make-prog  --without-make-prog  --srcdir=.  --curdir  --ruby=/home/dineshp/.rvm/rubies/ruby-2.2.1/bin/$(RUBY_BASE_NAME)  --with-gl-dir  --without-gl-dir  --with-gl-include  --without-gl-include=${gl-dir}/include  --with-gl-lib  --without-gl-lib=${gl-dir}/lib  --with-zlib-dir  --without-zlib-dir  --with-zlib-include  --without-zlib-include=${zlib-dir}/include  --with-zlib-lib  --without-zlib-lib=${zlib-dir}/lib  Command 'qmake ' not available    extconf failed, exit code 1    Gem files will remain installed in /home/dineshp/.rvm/gems/ruby-2.2.1@rails420/gems/capybara-webkit-1.11.1 for inspection.  Results logged to /home/dineshp/.rvm/gems/ruby-2.2.1@rails420/extensions/x86_64-linux/2.2.0/capybara-webkit-1.11.1/gem_make.out  An error occurred while installing capybara-webkit (1.11.1), and Bundler cannot continue.  Make sure that `gem install capybara-webkit -v '1.11.1'` succeeds before bundling.  

As the above error shows: Command 'qmake ' not available, I tried installing qt using the following command after referring this:

sudo apt-get install libqt4-dev libqtwebkit-dev  

When I type qmake --version, I get the following message:

The program 'qmake' is currently not installed. You can install it by typing:  sudo apt-get install qtchooser  

As I know I have installed qt, I tried running the qtchooser -list-versions and I get the following list of qt versions in my system:

4  5  default  qt4-i386-linux-gnu  qt4-x86_64-linux-gnu  qt4  qt5-x86_64-linux-gnu  qt5  

Why I am not able to access qmake commands from terminal in Ubuntu 14.04 ?

Rails - two javascripts files are generated for one controller and hence js function is executing twice

Posted: 14 Aug 2016 01:17 AM PDT

Context I am learning rails and trying to create a simple webpage that has file button and submit button. When user clicks the submit button, the browser should display either "Select one or more files" or should display the size of file selected.

Issue The webpage is alerting the same message twice. For example,if I dont select a file and click submit, I get the alert "Select one or more files" twice.When I used debug, the control traverses through both the javascript that got generated for controller and hence displays message twice.

  1. Why two javascript got generated for same coffeescript for a controller?
  2. How do I stop two files from getting generated?

Additional Details

I have a controller main_page.I wrote a coffeescript for main_page controller. However,When I launched the webpage, I can see two javascript file

<script src="/assets/main_page.js.self-fce0f72385b89610aec7efdb8340722a1a1c99772f861b071c3e56ffff373e96.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/main_page.self-08dee8c4f626e100c3f8d2edde72d6a239b69493ee184c06820641df835a4b8c.js?body=1" data-turbolinks-track="true"></script>  

I checked in developer tools, the javascript code in both are same.

The coffeescript code is as below -

@checkFileSize = ->    x = document.getElementById("file_tag")  if 'files' of x    if x.files.length is 0      txt = "Select one or more files."    else      for item in x.files        if 'size' in item          txt += "size: " + file.size + " bytes <br>"    alert txt    $ ->    $("#submit_tag").click (e) ->      e.preventDefault();      checkFileSize()  

application.html.erb

 <!DOCTYPE html>   <html>     <head>       <title>Learning Rails</title>       <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>       <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>       <%= csrf_meta_tags %>     </head>     <body>       <%= yield %>=     </body>   </html>  

Please let me know, if you need additional details.

EDITED application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details    // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require turbolinks  //= require raphael  //= require morris  //= require_tree .  

Asset Lib Snapshot - enter image description here

Leaflet layer ordering after zooming

Posted: 13 Aug 2016 11:15 PM PDT

I have problems to understand how layer ordering in leaflet works and I'm completly new to Javascript/Coffeescript.

The code I'm working on is part of a Ruby&Rails app and can be found here. The idea is to

  • setup a osm basemap
  • add a heatmap of points
  • let the user select a rectangular area as a selection tool for further stuff to happen inside the Rails app
  • react to user zooming by changing the heatmap to a marker-cluster setup

The problem: Zooming causes the layers to be redrawn. So the user selection rectangle ends up under the transparent layers of the heatmap. I want it to stay on top. I tried to apply featuregroup.bringToBack() and featuregroup.bringToFront()m but it's not working as expected.

I wrote some example code with jsfiddle for this stackoverflow question to illustrate the problem and my approach in a more simple way. You need leaflet.js, leaflet.css and leaflet-heat.js for this to work:

# prepare basemap  osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'  osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors'  osm = L.tileLayer(osmUrl,    maxZoom: 18    attribution: osmAttrib)    # initialize the map with basemap  map = L.map('map').setView([    17    75  ], 5).addLayer(osm)    # coordinate vectors  lat = [14, 15, 16, 18, 19, 20]  lng = [72, 73, 74, 76, 77, 78]    # function: layer arrangement in relation to zoom state  arrange_layers = ->    if map.getZoom() > 5      console.log "1"      heatItem.bringToFront()    if map.getZoom() <= 5      console.log "2"      heatItem.bringToBack()    return    #function: react to user zooming  map.on 'zoomend', (e) ->    arrange_layers()    console.log map.getZoom();    return    # add circles to map  for lati in lat    for lngi in lng       L.circle([         lati         lngi        ], 50000,         color: 'black'         fillColor: '#black'         fillOpacity: 0.5).addTo(map)    # add heatmap to map  heatItem = new (L.FeatureGroup)  heat = L.heatLayer([    [      15      73      3000    ]    [      19      77      10000    ]  ], radius: 25).addTo(heatItem)  heatItem.addTo(map)  

Rails form_for many to many relationship

Posted: 13 Aug 2016 10:14 PM PDT

Please forgive me if this is a simple question. I've spent some time searching SO and have not fund a clear answer for this question. I'm also new to rails.

I have a regular old many to many relationship with an associative table in between. The relationships are A workout has many exercises An exercise belongs to many workouts.

I have 2 forms, one to create new workouts, and another to create new exercises. The 3rd form will be used to populate the associative table "workout_exercises". This will allow users to add exercises to multiple workouts.

I want a user to pick a workout, where they will be presented with a list of exercises filtered by a category drop down (which I have working). a checkbox selected on the form submission will grab the id's submitted for the exercises. The problem is the ID for the workout is not available from this form.

My models look like this

class Exercise < ActiveRecord::Base     belongs_to :category     belongs_to :workout_exercise  end    class Workout < ActiveRecord::Base     belongs_to :workout_exercise   end    class WorkoutExercise < ActiveRecord::Base      has_many :workouts      has_many :exercises   end  

controller action looks like this

def exercises        @workout_exercise = WorkoutExercise.new        respond_to do |format|           format.js {              @workout = #?? I don't have the workout ID available from the request              @exercises = Exercise.where(category_id: params[:id]) #this is for the dropdown filter :id grabed on select change             }        end     end  

I was thinking a possible option to this problem might be to use a nested route somehow?

Thanks in advance for any help!

Rails + Cloudinary Gem - How to add rounding step to cl_image_tag?

Posted: 14 Aug 2016 06:47 AM PDT

I'm using the cloudinary gem and cl_image_tag helper method to display my images.

<%= cl_image_tag(picture.image, :width => :auto, :dpr => :auto, :responsive_placeholder => "blank") %>  

As you can see, I'm adding the :width => :auto option in the helper method. This helper will create a link of this sort

<img data-src="http://res.cloudinary.com/travelcrumbs/image/upload/dpr_auto,w_auto/v1470821928/hero%20image/footsteps.jpg" class="cld-responsive">  

The :width => :auto option creates a w_auto request in the created URL. This way an image with appropriate (depending on the container) width is being requested from the cloudinary CDN. But I would like to change the rounding step to 200px (so that it only requests a different image every 200px.) and need to get a w_auto:200 request in the URL.

How do I do that?

Rails 5 error: No route matches [DELETE] "/comments"

Posted: 13 Aug 2016 10:44 PM PDT

I am currently trying to delete a comment the exact same way I can delete a post in my application. However, for some reason the exact same code does not seem to work for my comments an returns the following error:

No route matches [DELETE] "/comments"

def destroy     @post = @comment.post     @comment.destroy     respond_to do |format|        format.html { redirect_to @post, notice: 'Comment was successfully destroyed.' }        format.json { head :no_content }     end  end  

This is what my model looks like:

class Comment < ApplicationRecord      belongs_to :post      belongs_to :user  end  

This is what my route looks like:

Rails.application.routes.draw do     resources :posts     resources :users     resources :comments, only: [:create, :destroy]       #signup and register workflow     get '/signup' => 'users#new'     get '/login' => 'sessions#new'     post '/login' => 'sessions#create'     delete '/logout' => 'sessions#destroy'  end  

This is what my link in my view looks like (Slim):

   - @comments.each do |comment|        .comment-container.level-0          p           a href="/users/#{comment.user_id}" = comment.user.first_name          | :           = comment.comment          - if comment.user == current_user            .icon-delete              = link_to "Delete", comment, method: :delete, data: { confirm: 'Are you sure?' }      end      hr      h3 Write a new comment      = bootstrap_form_for(@comment) do |c|        .field          = c.text_field :comment        .field          = c.hidden_field :user_id, :value => current_user.id          = c.hidden_field :post_id, :value => @post.id        .actions          = c.submit  

Error installing SQlite during installation of Beef in windows

Posted: 13 Aug 2016 09:44 PM PDT

I am trying to install BEEF in Windows 10 PC by following the instructions given here: https://github.com/beefproject/beef/wiki/Installation

I am stuck in the last step while doing bundle install. I keep on getting this error:

Installing do_sqlite3 0.10.17 with native extensions    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        E:/Ruby22-x64/bin/ruby.exe -r ./siteconf20160814-9372-uyjql9.rb extconf.rb  checking for sqlite3.h... no  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:          --with-opt-dir          --without-opt-dir          --with-opt-include          --without-opt-include=${opt-dir}/include          --with-opt-lib          --without-opt-lib=${opt-dir}/lib          --with-make-prog          --without-make-prog          --srcdir=.          --curdir          --ruby=E:/Ruby22-x64/bin/$(RUBY_BASE_NAME)          --with-sqlite3-dir          --without-sqlite3-dir          --with-sqlite3-include          --without-sqlite3-include=${sqlite3-dir}/include          --with-sqlite3-lib          --without-sqlite3-lib=${sqlite3-dir}/lib    extconf failed, exit code 1    Gem files will remain installed in E:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/do_sqlite3-0.10.17 for inspection.  Results logged to E:/Ruby22-x64/lib/ruby/gems/2.2.0/extensions/x64-mingw32/2.2.0/do_sqlite3-0.10.17/gem_make.out  Using dm-do-adapter 1.2.0  Using dm-migrations 1.2.0  Using dm-serializer 1.2.2  Using qr4r 0.4.1  Using sinatra 1.4.7  Using rubydns 0.7.3  An error occurred while installing do_sqlite3 (0.10.17), and Bundler cannot  continue.  Make sure that `gem install do_sqlite3 -v '0.10.17'` succeeds before bundling.  

I have tried all workarounds I got by googling like compiling the header file from source and running gem install sqlite3. But none of them work.

Can someone please help me out with this? Any help will be appreciated.

Ruby: Change button text to icon

Posted: 13 Aug 2016 11:41 PM PDT

My submit button for a comment displays a grey dull button that says "Create Comment". I want to instead display an icon.

I have tried...

<%= f.submit do %>    <i class="fa fa-paper-plane-o" aria-hidden="true"></i>  <% end %>  

...with no luck

Creating a series of modals dynamically

Posted: 13 Aug 2016 08:33 PM PDT

I am trying to execute two javascript statements through rails response. Just the first one (refreshing the page) is executing.

render js: "window.location='/';$( window ).load( $('#applybutton').click());"   

The second statement where I am trying to trigger a click does not work. If I run the second statement in browser console after the page reloads, it works fine.

The problem I am trying to solve here is to render a bootstrap modal after a first modal sends an ajax request which is processed successfully, which happens in the controller that has the above statement. In order to do that I have tried the above statement and have also tried

render js: "window.location='/';$($('#user_type_modal').modal());"   

The second modal is not ready until , the first modal is submits request , hence the page needs to be reloaded so that the partial is ready.

I have seen solution in this question : rails 4 bootstrap 3 ajax modal

However , its just going to complicate things for me , as its not just a second modal , but a series of modals that are linked together which are dependent on the sucessfull processing of ajax request from first modal.

These interlinked modals( generated out of partials) work fine in another part of the website , where the user is already signed in.

Ruby on Rails - User object showing nil fields even though they are filled

Posted: 13 Aug 2016 10:59 PM PDT

I'm having a weird problem with getting my user registration to work in Rails. When I create a user, it will show all its fields but the password_digest being nil, but when I type something like "u.email", the email will show up. However, it doesn't want to save the user, I assume because it thinks it doesn't meet all the validation requirements.

Some rails console fiddling:

irb(main):003:0> u = User.new({username: "askddkasd", email: "a@a.a",       password: "meowmeowmeow", password_confirmation: "meowmeowmeow"})  => #<User id: nil, username: nil, email: nil, password_digest:       "$2a$10$eWhQdOCLXfmcGrrRdigSFeENUeAEaQ6xJ7U08k7g3gZ...", salt: nil>  irb(main):002:0> u.save      (0.2ms)  BEGIN        User Exists (0.3ms)  SELECT  1 AS one FROM `users` WHERE `users`.`username` = BINARY 'askddkasd' LIMIT 1        User Exists (0.2ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY 'a@a.a' LIMIT 1      (0.1ms)  ROLLBACK  => false  irb(main):022:0> u.username  => "askddkasd"  irb(main):023:0> u.email  => "a@a.a"  

As you can see, the fields appear nil, but I can access their values. Here is my user model:

class User < ApplicationRecord      has_secure_password        attr_accessor :username, :email, :password, :password_confirmation        validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }      validates :email, :presence => true, :uniqueness => true      validates :password, :confirmation => true #password_confirmation attr      validates_length_of :password, :in => 6..20, :on => :create        after_save :clear_password        def password=(password)          self.password_digest = BCrypt::Password.create(password)      end        def is_password?(password)          BCrypt::Password.new(self.password_digest) == password      end        def clear_password          self.password = nil      end        def self.authenticate(username_or_email="", login_password="")        if username_or_email.include? '@'          user = User.find_by_email(username_or_email)        else          user = User.find_by_username(username_or_email)        end          if user && user.is_password?(login_password)          return user        end        return false      end  end  

Has anyone had this problem before? If so, how did you resolve it?

Update: Could it be because I have username and email as accessors? So those values don't actually get to the username/email fields to be stored in the database?

Rails Active Record Class.all returns ActiveRecord_Relation, but no other methods work

Posted: 13 Aug 2016 08:06 PM PDT

I have a table called vocabulary_words.

VocabularyWord.all # #<#<Class:#<VocabularyWord::ActiveRecord_Relation:0x007ff2719ebdb0>>:0x3ff938cf5ed8>    VocabularyWord.count # ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block    VocabularyWord.new # ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block  

This only happens with my test database. My development database works just fine. Why am I able to call .all but can't do anything else with it?

Better way to set the user that last updated a model, when the model has many childs

Posted: 13 Aug 2016 08:14 PM PDT

I have a model that I'll call Parent. When this model is updated, I register which User did this last update on the parent model. I do this at the ParentsController like this:

def update    @parent = Parent.find(params[:id])    @parent.assign_attributes(params[:parent])    @parent.last_editor = current_user      if @parent.save      # continue....  

This works well. The controller tells the model who is the current_user. The concerns are separated well.

But the Parent model has many different child models and I want to update the last_editor of the Parent when its childs are updated. (The last_editor is a User).

I could do this:

class ChildOnesController    # ...    def create      @child_one = ChildOne.new(params[:child_one])        if @child_one.save        @child_one.parent.update_attribute(last_editor: current_user)      else        # ...      end    end      def update       @child_one = ChildOne.find(params[:id])        if @child_one.update_attributes(params[:child_one])        @child_one.parent.update_attribute(last_editor: current_user)        # continue....      end    end      def destroy        # Destroy...then      @child_one.parent.update_attribute(last_editor: current_user)      # ...    end  

The main problem is: As my Parent model has various child models, I'll have to add those lines to every child model controller.

Is there a better, more concise way to do this?

Thanks a lot for any hint!!!

Ruby on Rails: How to define a controller definition per shim?

Posted: 13 Aug 2016 10:11 PM PDT

First time asking something here on StackOverflow. So excited!

Basically, I'm wondering what the correct design pattern is for what I'm trying to accomplish. I have all my code working but was wondering it there's a more elegant, "RoR Way" to put it all together. For a language/framework so beautiful, it just feels like I've done this wrong:

I have a single master layout page ("WeekSummary") I'm using to display a bunch of "DaySummary" shims. All shims derive from the same template "_day_summary.html.erb."

On WeekSummary, I'm able to pass variables to individual shims fairly easily, eg:

<%= render 'layouts/day_summary', date: '2016-08-12' %>  <%= render 'layouts/day_summary', date: '2016-08-11' %>  

But now I'm having trouble invoking a "day_summary" controller definition per each shim. Essentially, at this point in the render lifecycle, I believe I've already passed through the "C" part when the RoR engine called my "week_summary" definition (in which I did hold some business logic). But now I want the RoR engine to go back to the controller and call a "day_summary" controller definition per each shim I've defined on WeekSummary view page. I would like all variables/definitions to be then locally scoped to each shim (so I can reuse the same var names, etc).

I wasn't able to figure out how to do that though so right now I've simply dumped all my shim-specific business logic at the top of the "_day_summary.html.erb" in a massive <% %> block. Having so much business logic there in a View shim seems wrong though.

I hope this made sense. Does anyone have any suggestions for how to properly do this? Essentially, I'm trying to encapsulate the rendering of each shim into its own MVC lifecycle/pattern, if that makes sense. Thank you!

Edit: In response to kcdragon's code request on what's happening inside each shim: So, for example, for each day_summary shim, I wish to calculate that day's pnl.

At the top level, in the week_summary controller def, I get all transactions:

@transactions = Transaction.all.order('ticker', 'date DESC')  

Then in each shim, I filter @transactions by only the date I care about for that shim. Thus, a sample of each shim's business logic includes the below-- in this example, calculating that day's PnL:

transactions = @transactions.where(date: '2016-08-08')  pnlHash = Hash.new  totalPnl = 0  transactions.each do |t|    if !pnlHash.key?(t.ticker)      pnlHash[t.ticker] = t.pnl     else       pnlHash[t.ticker] += t.pnl     end     totalPnl += t.pnl  end  

<%= totalPnl %> is then rendered elsewhere on the shim.

There's other business logic too that happens in the shim, but this is a good representative sample.

Now, obviously at the top level (week_summary), I could "pre-process" all daily PnL calculations and then store them in some massive hashtable which I'd then use to extract values per day_summary shim. (In this example, I guess that'd be a true model of the week_summary view.) But I don't want to do that. I want to encapsulate day_summary into its own thing, where all its business logic and rendering is processed on the fly as week_summary renders. Hopefully that makes sense?

Edit2: For sake of clarity, here's what each day_summary shim looks like. On the week_summary view, five of these guys are rendered, each one corresponding to its respective date:

Here's what the day_summary shim looks like.

Assets not compiling

Posted: 13 Aug 2016 10:07 PM PDT

This is driving me crazy - changes to css on my rails site only update when I run rake assets:precompile.

Does anyone know how to fix this, so assets will get compiled as they are changed?

I have a hunch the issue is in this config/environments/development.rb file:

Rails.application.configure do    # Settings specified here will take precedence over those in config/application.rb.    config.assets.compile = true    # In the development environment your application's code is reloaded on    # every request. This slows down response time but is perfect for development    # since you don't have to restart the web server when you make code changes.    config.cache_classes = false      # Do not eager load code on boot.    config.eager_load = false      # Show full error reports and disable caching.    config.consider_all_requests_local       = true    config.action_controller.perform_caching = false      # Care if the mailer can't send.    config.action_mailer.raise_delivery_errors = true      # Print deprecation notices to the Rails logger.    config.active_support.deprecation        = :log    config.action_mailer.delivery_method     = :smtp    config.action_mailer.perform_deliveries  = true    config.action_mailer.default_url_options = { :host => "http://localhost:3000/" }    # SMTP settings for gmail    config.action_mailer.smtp_settings = {      address:              'smtp.gmail.com',      port:                 587,      domain:               'gmail.com',      user_name:            ENV['gmail_username'],      password:             ENV['gmail_password'],      authentication:       'plain',      enable_starttls_auto: true    }      # Raise an error on page load if there are pending migrations.    config.active_record.migration_error = :page_load      # Debug mode disables concatenation and preprocessing of assets.    # This option may cause significant delays in view rendering with a large    # number of complex assets.    config.assets.debug = true      # Asset digests allow you to set far-future HTTP expiration dates on all assets,    # yet still be able to expire them through the digest params.    config.assets.digest = true      # Adds additional error checking when serving assets at runtime.    # Checks for improperly declared sprockets dependencies.    # Raises helpful error messages.    config.assets.raise_runtime_errors = true      # Raises error for missing translations    # config.action_view.raise_on_missing_translations = true  end  

Here is the top of my assets/stylesheets/application.css file:

/*   * This is a manifest file that'll be compiled into application.css, which will include all the files   * listed below.   *   * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,   * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.   *   * You're free to add application wide styles to this file and they'll appear at the bottom of the   * compiled file so the styles you add here take precedence over styles defined in any styles   * defined in the other CSS/SCSS files in this directory. It is generally better to create a new   * file per style scope.   *   *= require_tree .   *= require_self   */  

As well as the top of application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require_tree .  

Edit: I should add that this only became a problem once I removed bootstrap...

Ruby on rails Production mode on apache2

Posted: 13 Aug 2016 11:16 PM PDT

I am trying to switch from development mode to production my project in ruby on rails. Do I really need to install passenger? I have already apache server running in the system. Please advise. Thanks.

No comments:

Post a Comment