Rails: using the calendar_date_select gem - ruby-on-rails

Environment: Rails 3.2.3, ruby 1.9.3-p125
My gemfile has the following in it:
gem 'calendar_date_select'
my layouts/application.html.erb has the following statement (as the last statement in the head section):
<%= calendar_date_select_includes %>
I installed the gem via gem install calendar_date_select
and ran rake bundle:install
I read the documentation, and some of the responses on StackOverflow, and here's what I ended up putting in my view:
<%= form_for(#panel) do |f| %>
.......
Start Date/Time: <%= f.calendar_date_select :start_time, :iso_date => true %>
I am getting the following error message:
undefined method `calendar_date_select' for #<#:0x007fae3b136938>
Any ideas?

I've switched from using that gem to just using jqueryUI which has the same functionality.
To do that:
view
= f.text_field :content_date, id: 'datepicker', size:10
= f.time_select :content_date, :ignore_date => true # Added later. not shown in screenshot
Gemfile
# Nothing - jquery & jqueryUI are now the default.
# Check web pages to see what really gets included (in the header).
application.js
%script
# The main code
$(function() {
$( "#datepicker" ).datepicker();
});
# This makes the pop-up show the actual db date by fixing a format difference.
$(function (){
var dateInput = $("#datepicker");
var format = 'yy-mm-dd';
dateInput.datepicker({dateFormat: format});
dateInput.datepicker('setDate', $.datepicker.parseDate(format, dateInput.val()));
});

Use this code to enable time in calender select tag
<%= f.calendar_date_select "date", :time => true , :readonly=>true, :popup=>"force" %>

Related

Spree deface override tutorial

I am following the Spree deface overrides developer guide: http://guides.spreecommerce.com/developer/deface_overrides_tutorial.html
My code matches their's exactly, but I keep getting this error. I looked all around but I didn't see anyone else having this problem or anything similar at all:
undefined method `content_tag' for Spree:Module
I am running Rails 4.0.2 and ruby 1.9.3 (it's possible that the tutorial wasn't updated for rails 4?)
here's my code:
app/overrides/add_sale_price_to_product_edit.rb
Deface::Override.new(:virtual_path => 'spree/admin/products/_form',
:name => 'add_sale_price_to_product_edit',
:insert_after => "erb[loud]:contains('text_field :price')",
:text => "
<%= f.field_container :sale_price do %>
<%= f.label :sale_price, raw(Spree.t(:sale_price)) %><span>*</span>
<%= f.text_field :sale_price, :value =>
number_to_currency(#product.sale_price, :unit => '') %>
<%= f.error_message_on :sale_price %>
<% end %>
")
app/models/spree/product_decorator.rb
module Spree
Product.class_eval do
delegate_belongs_to :master, :sale_price
end
end
You're getting the error because the translation for Spree.t(:sale_price) is not specified. This is failing because Rails 4.0.2 made some changes to the I18n API . You have a few choices.
Add a translation for the missing tag and remember that this content_tag issue is caused by this crazy bug.
Downgrade to Rails 4.0.0 (not recommended)
Upgrade spree to the 2-1-stable branch (or wait until 2.1.4 is released)
Apply this change to your local Spree installation. It should correct this issue.
Any of those should get you working again.

rails 4 with CKeditor

I cannot get the galetahub ckeditor gem to work with Rails 4 for me. I searched for any problems online but cannot find any. I'm following the instructions exactly.
I include gem "ckeditor" in my Gemfile
I include gem "carrierwave" and gem "mini_magick"
I run rails generate ckeditor:install --orm=active_record --backend=carrierwave
I run rake db:migrate
Inside application.rb I include config.autoload_paths += %W(#{config.root}/app/models/ckeditor)
Inside routes.rb I have mount Ckeditor::Engine => '/ckeditor'
I'm using SimpleForm so I paste the following ERB <%= f.input :description, as: :ckeditor %> in my view.
And I think that's it. But my text area does not convert to a CKeditor area for some reason.
STEP 1: Add gem 'paperclip' and gem "ckeditor" in your gemfile.
STEP 2: Bundle Install.
STEP 3: rails generate ckeditor:install --orm=active_record --backend=paperclip
STEP 4: Place config.autoload_paths += %W(#{config.root}/app/models/ckeditor) in application.rb
STEP 5: Place mount Ckeditor::Engine => "/ckeditor" if not present in routes.rb already and run db:migrate
STEP 6: Open application.html.erb and place this <%= javascript_include_tag 'ckeditor/ckeditor.js' %> in header.
STEP 7: Place this in footer(above the body tag) in application.html.erb
<script type="text/javascript">$(document).ready(function() {
if ($('textarea').length > 0) {
var data = $('textarea');
$.each(data, function(i) {
CKEDITOR.replace(data[i].id);
});
}
});</script>
STEP 8: Restart the WEBrick SERVER.
That's it.
Else
Download the CKEditor Zip file, extract the files and place them in the sub directory “javascripts/ckeditor”, add the main JS file to the layout..
javascript_include_tag 'ckeditor/ckeditor.js'
Place this in footer(above the body tag) in application.html.erb
<script type="text/javascript">$(document).ready(function() {
if ($('textarea').length > 0) {
var data = $('textarea');
$.each(data, function(i) {
CKEDITOR.replace(data[i].id);
});
}
});</script>
I have the same problem using rails 4 and apparently the problem is that the form helper
form.cktext_area
Or in your case
f.input :description, as: :ckeditor
it's not generating what it supposed to generate, and you don't have to load the editor manually, the only thing you need to do is to is to add the class 'ckeditor' to your textarea and it will load automatically, like this:
f.cktext_area :body, :class => 'ckeditor'
Meanwhile the Galetahub gem has been updated, but it has to be updated in your app manually. Read the github page: https://github.com/galetahub/ckeditor.
ajkumar basically answered the question well already, but if you are still lost, all you need to do is download the js file, include it in your html, have a script snippet included in the HTML to activate ckeditor on a certain textarea tag ID, and then change the class of the "textarea" tag you want to change to ckeditor. Quick sample below
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
The galetahub gem is currently broken on Rails 4. This one is working fine though: https://github.com/tsechingho/ckeditor-rails
In case you are having trouble making it work with active admin, make sure to put this:
config.register_javascript 'ckeditor/ckeditor.js'
config.register_javascript 'ckeditor/init.js'
Into config/initializers/active_admin.rb

gmap4rails in ActiveAdmin: maps does not appear

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.

Multiple files upload with Rails 3 and paperclip on heroku

I need an interface on my Rails 3 app to upload multiple files to Amazon S3 (because i'm on heroku), possibly with progress bars.
I've easily managed how to set up paperclip and upload single files, but i'm really lost now on how to go ahead.
Please can you give me some advices? It's 2 days i'm searching across all the internet, but i can't find a working solution
** EDIT **
I really can't understand... I'm going mad 'cause I'm losing too many hours on this... please help me.
If I try to open the example app cited by Johnny I only get this (and in my app it is the same):
Where is the UI?
Is there something wrong on my browser?
** EDIT 2 **
Here on GitHub you can find my testapp... please can you explain me why the damn upload UI is not showing up? Thanks!
** EDIT 3 **
Thank you very much Johnny, i wasn't aware of the fact that jquery and prototype can't live together.
Now the plugin is showing up correctly, but as a try to upload something it creates a new "upload" record, but its attachment field is blank, and the files are not on s3.
This is what the console is saying:
Started POST "/uploads" for 127.0.0.1 at 2011-06-27 16:17:22 +0200
Processing by UploadsController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"GesRBTiZR1f2LV/bAeAdxWqF++gxcDJw4pPGStYGsH8=", "upload"=>{"attachment"=>[#<ActionDispatch::Http::UploadedFile:0x000001032834b8 #original_filename="animal-tiger-66550.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"upload[attachment][]\"; filename=\"animal-tiger-66550.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/var/folders/Qj/QjEqvUUNGTmuki5SXOaaG++++TI/-Tmp-/RackMultipart20110627-1818-1syiex9>>]}}
AREL (0.5ms) INSERT INTO "uploads" ("attachment", "created_at", "updated_at", "attachment_file_name", "attachment_content_type", "attachment_file_size", "attachment_updated_at") VALUES (NULL, '2011-06-27 14:17:23.049136', '2011-06-27 14:17:23.049136', NULL, NULL, NULL, NULL)
[paperclip] Saving attachments.
Completed 200 OK in 64ms (Views: 4.2ms | ActiveRecord: 0.7ms)
You can look at jQuery-File-Upload. Demo here and rails 3/Paperclip setup here.
Edit: As #apneadiving mentioned, the library has been updated to version 5. The script you have is for verison 4. You should try modifying this to work with PaperClip. Copy-pasting the majority of the example code into my app (with a few modifications) worked for me:
#app/public/javascripts/application.js
$(function () {
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
// Load existing files:
$.getJSON($('#fileupload form').prop('action'), function (files) {
var fu = $('#fileupload').data('fileupload');
fu._adjustMaxNumberOfFiles(-files.length);
fu._renderDownload(files)
.appendTo($('#fileupload .files'))
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
});
});
// Open download dialogs via iframes,
// to prevent aborting current uploads:
$('#fileupload .files a:not([target^=_blank])').live('click', function (e) {
e.preventDefault();
$('<iframe style="display:none;"></iframe>')
.prop('src', this.href)
.appendTo('body');
});
});
#app/controllers/uploads_controller.rb
def create
#upload = Upload.new(params[:upload])
if #upload.save
render :json => [{
:pic_path => #upload.attachment.url.to_s ,
:name => #upload.attachment.instance.attributes["picture_file_name"]
}], :content_type => 'text/html'
else
render [:json => { :result => 'error'}], :content_type => 'text/html'
end
end
#app/views/uploads/new.html.haml
%link#theme{:href => "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/base/jquery-ui.css", :rel => "stylesheet"}
= stylesheet_link_tag 'jquery.fileupload-ui'
#fileupload
= form_for Upload.new, :html => { :multipart => true } do |f|
.fileupload-buttonbar
%label.fileinput-button
%span Add files...
= f.file_field :attachment, :multiple => true
%button.start{:type => "submit"} Start upload
%button.cancel{:type => "reset"} Cancel upload
%button.delete{:type => "button"} Delete files
.fileupload-content
%table.files
.fileupload-progressbar
%script#template-upload{:type => "text/x-jquery-tmpl"}
%tr{:class => "template-upload{{if error}} ui-state-error{{/if}}"}
%td.preview
%td.name ${name}
%td.size ${sizef}
{{if error}}
%td.error{:colspan => "2"}
Error:
{{if error === 'custom_failure'}}Custom Error Message
{{else}}${error}
{{/if}}
{{else}}
%td.progress
%div
%td.start
%button Start
{{/if}}
%td.cancel
%button Cancel
%script#template-download{:type => "text/x-jquery-tmpl"}
%tr{:class => "template-download{{if error}} ui-state-error{{/if}}"}
{{if error}}
%td
%td.name ${name}
%td.size ${sizef}
%td.error{:colspan => "2"}
Error:
{{if error === 1}}File exceeds upload_max_filesize (php.ini directive)
{{else}}${error}
{{/if}}
{{else}}
%td.preview
{{if thumbnail_url}}
%a{:href => "${url}", :target => "_blank"}
%img{:src => "${thumbnail_url}"}/
{{/if}}
%td.name
<a href="${url}"{{if thumbnail_url}} target="_blank"{{/if}}>${name}
%td.size ${sizef}
%td{:colspan => "2"}
{{/if}}
%td.delete
%button{"data-type" => "${delete_type}", "data-url" => "${delete_url}"} Delete
Edit
Had a quick look at your app, the problem is that you are mixing prototype with jquery. The easiest way around this is to switch to jQuery using jquery-rails.
#Gemfile
gem 'jquery-rails'
Next, run bundle install and then rails g jquery:install.
Then change your app/views/layouts/application.erb to this:
<%= stylesheet_link_tag :all %>
<%= csrf_meta_tag %>
<%= javascript_include_tag 'jquery.min' %>
<%= javascript_include_tag 'jquery-ui-1.8.13.custom.min' %>
<%= javascript_include_tag 'jquery.tmpl.min' %>
<%= javascript_include_tag 'jquery.iframe-transport' %>
<%= javascript_include_tag 'jquery.fileupload' %>
<%= javascript_include_tag 'jquery.fileupload-ui' %>
<%= javascript_include_tag 'jquery_ujs' %>
<%= javascript_include_tag 'application' %>
Note that I removed the
<%= javascript_include_tag :defaults %>
So that I can specify the order in which jquery, jquery_ujs, and application are loaded.
I've begun with a very similar task recently, and the swf plugin (at least the more recent one) will indeed let you update paperclip's record. It has callbacks for just about everything you'd need to extend.
:onUploadComplete (upload_options,event)
Here's Nathan Colgate's gist on the matter. He just makes a remote call to the rails server once the upload is finished telling it of the locations for the paperclip attachment.
from his uploadCompleteHandler
var uploadCompleteHandler = function(upload_options,event){
$.ajax({
url: '<%= notify_rails_of_successful_upload_path(:format => :js)%>',
global: false,
type: 'POST',
data: ({
'authenticity_token' : '<%= form_authenticity_token %>',
'upload' : {
'file_file_name' : upload_options.FileName,
'file_file_size' : upload_options.FileSize,
'file_content_type' : upload_options.ContentType
}
}),
dataType: 'script'
}
)
};
I'm not sure if this exact callback gets triggered for each file; it definitely looks like it would. But he passes everything paperclip needs back through an ajax request. filename,size,content-type. This way all that gets sent to heroku is some text about the file, sparing your app a good amount of work by giving it to the client.
edit: flash is the only way I've found to avoid sending a lot of data through heroku to s3. There are a few html5/js-only uploaders that might be able to get the job done, but the ones I have found are still pretty ripe on the dev tree.
As per Heroku support, see this.
Paperclip & multiple files upload, although not S3 specific.
View: (notice the array blog_post[avatars][])
<form accept-charset="UTF-8" action="/blog_posts" enctype="multipart/form-data" id="new_blog_post" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="<%=form_authenticity_token %>" />
</div>
<p><input id="blog_post" name="blog_post[avatars][]" type="file" multiple /></p>
<p><input name="commit" type="submit" value="Upload" /></p>
</form>
Controller:
# POST /blog_posts
# POST /blog_posts.json
def create
#blog_post = BlogPost.new(params[:blog_post])
#blog_post.avatars.each do |avatar|
each_blog_post = BlogPost.new
each_blog_post.avatar = avatar
if each_blog_post.save
end
end
end
Model:
class BlogPost < ActiveRecord::Base
attr_accessible :title, :avatar, :avatars
has_attached_file :avatar
attr_accessor :avatars
end

Links with data-remote="true" not processing as JSON

I am testing creating a link_to with :remote=> true to get the ajax remote link handling.
<%= link_to "Get Books", "/books", :remote=> true %>
The helper for rails3 resolves the code correctly in the view and I get as source:
Get Books
And I have the default javascript included:
<%= javascript_include_tag :defaults %>
And the source head resolves as:
<script src="/javascripts/jquery.js?1302296105" type="text/javascript"></script>
<script src="/javascripts/rails.js?1302139751" type="text/javascript"></script>
<script src="/javascripts/application.js?1305999509" type="text/javascript"></script>
And in the controller I have:
respond_to :html, :json
However when I click the link it loads as regular link, not ajax and on the server log:
Processing by BooksController#index as HTML
What am I missing?
Make sure that you have installed the jQuery UJS Plugin:
Add this to your gemfile:
gem 'jquery-rails', '>= 1.0.3'
And then run:
bundle install
rails g jquery:install
I had a similar issue: I expected a remote link to be processed as JS request but Rails somehow was processing it as HTML.
The problem is we don't specify a format and then Rails could choose any of the formats depending on the server configuration.
TL;DR; Specify the request type when using remote:
<%= link_to "Get Books", "/books", data: {remote: true, type: "script"} %>

Resources