gmap4rails in ActiveAdmin: maps does not appear - ruby-on-rails

In try to use gmaps4rails in my ActiveAdmin / Rails app. To do so, I have added the following in my Gemfile:
gem 'gmaps4rails'
and ran a "bundle". I updated the 'show' method in app/admin/device.rb file with:
show do
attributes_table do
row :name
end
# Get device location
#markers = Location.all.to_gmaps4rails
div do
render "map"
end
end
In the app/views/admin/devices/_map.html.erb I have the following code:
<%= stylesheet_link_tag 'gmaps4rails' %>
<%= gmaps4rails(#markers) %>
<%= yield :scripts %>
In app/assets/javascripts/application.js:
//= require gmaps4rails/gmaps4rails.googlemaps
//= require gmaps4rails/gmaps4rails.base
//= require jquery
//= require jquery_ujs
//= require_tree .
And in my app/models/location.rb:
class Location < ActiveRecord::Base
acts_as_gmappable
attr_accessible :latitude, :longitude
def gmaps4rails_address
"#{self.latitude}, #{self.longitude}"
end
def location
[:latitude, :longitude]
end
end
When I go on the show page of a device, the map does not shows up (all blank). Is there any configuration I missed ?
UPDATE
I have checked with chrome developer tools and noticed the following error:
Uncaught SyntaxError: Unexpected token ;
that make reference to the line:
Gmaps.map.markers = ;

Fix with the following:
div do
markers = Location.all.to_gmaps4rails
render "map", { :markers => markers }
end
and :
<%= stylesheet_link_tag 'gmaps4rails' %>
<%= gmaps({
"map_options" => { "zoom" => 2, "auto_adjust" => false},
"markers" => { "data" => markers }
})
%>
<%= yield :scripts %>

You have to load the Javascript files in the /config/initializers/active_admin.rb; search for the section:
# To load a javascript file:
# config.register_javascript 'my_javascript.js'
Also, I think you should add the CSS files (if is not appearing) into the same file.
Remember that ActiveAdmin manages its own Javascript file, named active_admin.js; you can try loading the Javascript files in this JS; some time ago I had a similar problem and I only was able to solve it adding the files in the initializer.

Related

Trying to include and use jquery file upload on rails throwing some errors?

I am trying to build an app with rails,
and in some module, I need to use custom file uploader,
I try to use jquery file upload, but somehow it throws me an error?
Here is what I have tried:
I added below codes to my gem file :
group :assets do
# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'jquery.fileupload-rails'
end
Note : I also tried to put my jquery file upload rails gem outside the asset group.
Added this to application js :
//= require jquery-fileupload/basic
When I try to access my view, I got this error
couldn't find file 'jquery-fileupload/basic' with type 'application/javascript'
oh FYI : I use rails 4.2.7
and windows 7 64 bits.
Forgot to mention I have run bundle install command too.
apt model
class Apt < ActiveRecord::Base
belongs_to :developer
belongs_to :area
has_many :floorplans
accepts_nested_attributes_for :floorplans
validates :apt_name, presence: true
validates :apt_address, presence: true
validates :apt_desc, presence: true
end
floorplan model
class Floorplan < ActiveRecord::Base
belongs_to :apt
mount_uploader :floorplanphoto, DefaultFileUploader
end
here is the request i did :
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"mDfWGOI+lVOrOBmi038/oRFRoM5NUdkOL4caWPp30U/pLD41X5kpIur8Mdyqau5vE58C74BzXY7fvGfZn3dgLA==",
"apt"=>{"apt_name"=>"twss",
"apt_address"=>"xccxcxcx",
"apt_lat"=>"",
"apt_long"=>"",
"thumbnail"=>#<ActionDispatch::Http::UploadedFile:0xaa3d018 #tempfile=#<Tempfile:C:/Users/lenovo/AppData/Local/Temp/RackMultipart20160811-9036-10xugyq.jpg>,
#original_filename="Hydrangeas.jpg",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"apt[thumbnail]\"; filename=\"Hydrangeas.jpg\"\r\nContent-Type: image/jpeg\r\n">,
"apt_desc"=>"xcxccxcx",
"developer_id"=>"3",
"area_id"=>"1",
"apt_status"=>"draft",
"facility_ids"=>["1",
""],
"poi_ids"=>["1",
""]},
"floorplans"=>{"floorplanphoto"=>[#<ActionDispatch::Http::UploadedFile:0xaa3cce8 #tempfile=#<Tempfile:C:/Users/lenovo/AppData/Local/Temp/RackMultipart20160811-9036-9d1kdg.jpg>,
#original_filename="Penguins.jpg",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"floorplans[floorplanphoto][]\"; filename=\"Penguins.jpg\"\r\nContent-Type: image/jpeg\r\n">]}}
as u can see there, i have floorplans inside my parameters, but it throw undefined method []' for nil:NilClass error
i tried to print my parameters on console and it did not have floorplans?
>> apt_params
=> {"apt_name"=>"twss", "apt_address"=>"xccxcxcx", "apt_lat"=>"", "apt_long"=>"", "thumbnail"=>#<ActionDispatch::Http::UploadedFile:0xaa3d018 #tempfile=#<Tempfile:C:/Users/lenovo/AppData/Local/Temp/RackMultipart20160811-9036-10xugyq.jpg>, #original_filename="Hydrangeas.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"apt[thumbnail]\"; filename=\"Hydrangeas.jpg\"\r\nContent-Type: image/jpeg\r\n">, "apt_desc"=>"xcxccxcx", "developer_id"=>"3", "area_id"=>"1", "apt_status"=>"draft", "facility_ids"=>["1", ""], "poi_ids"=>["1", ""]}
Try this:
Instead of using gem download the script and keep it in app/assets/javascripts folder. Suppose your script is inside folder jquery-fileupload and you need to load basic.js.
Now in application.js file in app/assets/javascript folder just add line //= require jquery-fileupload/basic. And restart your server.
This must solve your problem.
I think you should use remotipart gem
In Gemfile
gem 'remotipart'
In application.js
//= require jquery.remotipart
//= require_tree .
form
<%= form_for #apt, multipart: true, remote: true do |f|%>
<%= f.text_field :apt_name %>
<%= f.text_field :apt_address %>
<%= f.text_field :apt_desc %>
<%= f.fields_for :floorplans do |p| %>
<%= p.file_field :floorplanphoto, :multiple => true %>
<% end %>
<%= f.submit %>
<% end %>
app/controllers/apts_controller.js
def create
#apt = Apt.new(apt_params)
format_to do |format|
if #apt.save
apt_params[:floorplans].each do |a|
#floor_plans = #apt.floorplans.create!(a)
end
format.js {:locals => {:request => true}}
else
format.js {:locals => {:request => false}}
end
end
end
private
def apt_params
params.require(:apt).permit(:apt_name, :apt_address, apt_desc, floorplans: [:id, :post_id, :floorplanphoto])
end
views/users/create.js.erb
<% if remotipart_submitted? %>
if(<%= request %>)
// image is uploaded
else
// you can show here custom error msg
<% else %>
// Error in xhr request
<% end %>
There will be no changes in Model.
Hope this will help you.

cloudinary-direct upload from browser not uploading

When I try to upload a file directly to Cloudinary nothing happens. The file name in the selected file field is deleted and no file is added to my Cloudinary accounts' Media Library.
This is my index.html.erb file
<%= cloudinary_js_config %>
<%= form_tag(cardset_cards_path(#cardset, #card), :method => :post) do %>
<%= cl_image_upload_tag(:image_id) %>
<%= submit_tag 'Submit' %>
<% end %>
My application.js file
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require cloudinary
I do have the downloaded cloudinary.yml file with api_key and api_secret...
I'm using Rails 4, I haven't set my config.assets.enabled = false, so I belive I am using Asset Pipeline by default.
I believe I'm following the example in Cloudinary, but my Cloudinary Account Media Library doesn't show any file uploaded. I've tried adding :html => {:multipart => true}, but the same things happens nothing. I've tried different things in the controller to get the returned id, but since nothing is happening, I think I'd just be happy to get a file into my Cloudinary Media Library.
-hoping to rise from the dirt to the Clouds

How to use JQuery.noConflict() to fix conflict between JQuery and bootstrap in rails 3.2.12?

$.noConflict() was added to the application.js in rails 3.2.12 main app to solve the conflict between jquery and bootstrap. However it is not working as expected. Here is the application.js:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .
//= require bootstrap
$.noConflict();
When clicking add_more_contact link on the new customer form, there is an error in firebug:
ReferenceError: add_fields is not defined
add_fields is a js function defined in application.js:
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));
}
The calling of add_fields is done through a method in application_controller.rb:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render :partial => association.to_s, :locals => {:f => builder, :i_id => 0}
end
link_to_function(name, "add_fields(this, \"#{association}\", \"#{j fields}\")")
end
The code was working before bootstrap. What's wrong with the use of noConflict()? Do we need to add noConflict() to /views/layouts/application.html.erb as well? thanks for help.
UPDATE:
Here is the header of new customer page:
There is no conflict between jquery and bootsrap, contrary, jquery is a requirement for bootstrap to work.
But there is conflict between jquery-ui and bootstrap, which has been mitigated by a project at http://addyosmani.github.io/jquery-ui-bootstrap/ .
Anyway, I think the above code should work without calling noConflict.

Exporting a chart as image using lazy-highcharts gem

I am able to generate the charts using lazy highcharts but i want those charts to exported as images , here is my code which I am using to generate the charts
#fields= ReportHistory.all_history
#h = LazyHighCharts::HighChart.new('graph') do |f|
f.chart(:renderTo => 'container', :zoomType => 'x',:spacingRight=> 20)
f.title(:text => 'Reports')
f.xAxis(:title=>{:text => 'Days'}, :categories =>#fields.map{|x|x.Date}.last(limit=15))
f.yAxis(:title=>{:text=> 'Jobs_count', :type =>'integer' ,:max => 5000000})
f.series(:name =>'jobs_count', :data=> #fields.map{|x| x.jobs_count.to_i }.last(limit=15))
f.export(:type=> 'image/jpeg')
end
and in my view I to show the chart I have this
<%= high_chart("my_id", #h) %>
I want to have the effect like here where I can download the chart image using the export button.
First, you need to ensure that the export module is available and loaded by your view:
<%= javascript_include_tag "vendor/highcharts/highcharts.js" %>
<%= javascript_include_tag "vendor/highcharts/modules/exporting.js" %>
Second... there's nothing to do. As soon as the exporting modul is loaded, it will add the menu to export your graph.
Notes:
You may need to adapt the paths depending on your setup.
The exporting.js is part of the package you download from Highcharts.
You can add/update the following in your application.js
//= require highcharts/highcharts
//= require highcharts/highcharts-more
//= require highcharts/modules/no-data-to-display
//= require highcharts/modules/exporting
If you want also updated vendor assets of highcharts, you can run:
rake highcharts:update

Autocomplete Rails it is not working

What did I do wrong in this tutorial: https://github.com/grosser/simple_auto_complete
Here are my scripts by the way:
First I put this in my users_controller.rb
autocomplete_for :user, :username, :limit => 15, :order => 'created_at DESC'
In my routes.rb
namespace :profile do
resources :users, :only => [:index] do
collection do
post "search"
get "autocomplete_for_user_name"
end
end
In my application.js
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require jquery.autocomplete.js
//= require jquery.js
jQuery(function($){//on document ready
//autocomplete
$('input.autocomplete').each(function(){
var input = $(this);
input.autocomplete(input.attr('data-autocomplete-url'),{
matchContains:1,//also match inside of strings when caching
// mustMatch:1,//allow only values from the list
// selectFirst:1,//select the first item on tab/enter
removeInitialValue:0//when first applying $.autocomplete
});
});
});
In my views (app/views/profile/messages/compose.html.haml)
%div#page-info
%span#title
Compose
%span#desc
Compose a new Message
= form_for :message, :url => send_message_profile_messages_path do |message|
%label{:for => "friend"} To:
%br
=message.text_field :auto_user_name , :class => 'autocomplete', 'data-autocomplete-url'=> autocomplete_for_user_name_profile_users_path
%script{:type => "text/javascript"}jQuery(function($){//on document ready $('input.autocomplete').each(function(){var $input = $(this);$input.autocomplete($input.attr('data-autocomplete-url'));});});
//= collection_select(:message, :friend_id, #friends, :id, :username)
%br
%label{:for => "message"} Body:
%br
= message.text_area :message
%br
= message.file_field :attachment
%br
= submit_tag "Send", :confirm => "Are you sure?"
I am trying to autocomplete the users using their username (s)
Note: I had also installed the gem and I think there's no problem about that.
What am i doing wrong?
In view
remove the comment //on document ready from script, as it is all in single line I think it is commenting the whole line including js code.
or use alternate formatting
:javascript
//on document ready
jQuery(function($){
$('input.autocomplete').each(function(){
var $input = $(this);
$input.autocomplete($input.attr('data-autocomplete-url'));
});
});
add //= require_self to application file for adding its own js code.
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require jquery.autocomplete.js
//= require jquery.js
jQuery(function($){//on document ready
//autocomplete
$('input.autocomplete').each(function(){
var input = $(this);
input.autocomplete(input.attr('data-autocomplete-url'),{
matchContains:1,//also match inside of strings when caching
// mustMatch:1,//allow only values from the list
// selectFirst:1,//select the first item on tab/enter
removeInitialValue:0//when first applying $.autocomplete
});
});
});
Also try not to have white spaces between require.
rails warning in application.js says
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
I have been using this autocomplete it works great for me
https://github.com/crowdint/rails3-jquery-autocomplete

Resources