Uploading files using remote:true and remotipart + carrierwave gems - ruby-on-rails

I want to make remote file upload via remotipart + carrierwave. The problem is that my upload works, but it seems that it is uploaded as usual html. Or it is uploaded via ajax, but appropriate js file is not called.
I have a form_for with remote:true, and a corrseponding controller method create. Since the form is submitted as js, create.js.erb is used.
<% if #syllabus.errors.present? %>
$('#syllabus-errors').html('<%= escape_javascript(render 'layouts/error_messages', object: #syllabus) %>');
<% else %>
alert("ds");
$('#modal-body').html(<%= escape_javascript(render 'layouts/thanks') %>);
$('#syllabus-errors').html("");
<% end %>
Logs show this:
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendered layouts/_error_messages.html.erb (1.0ms)
Rendered syllabuses/create.js.erb (12.0ms)
It is kinda strange that error_messages are rendered earlier that create.js.erb, error_messages are being rendered inside create.js.erb.

I resolved this problem by adding this if:
<% if remotipart_submitted? %>
<% else %>
<% end %>
don't know why it didn't work without it.

Related

ActionController::UnknownFormat in Rails production only

I'm trying to display a flash message when I clicked the "check" button without re-rendering the entire page.
In the development mode, the code below does work but doesn't in the production mode.
Instead of staying in the main.html and displaying the flash message, it redirect me to "check" page.
The log console gave me debug messages below:
Completed 406 Not Acceptable in 2ms (ActiveRecord: 0.0ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/my_controller.rb:105:in `check'
Did I miss something for working on production mode?
main.html.erb
<div class="check"><%= render partial: 'check' %></div>
<%= f.submit :Check, class: "btn btn-default", remote: true, formaction: app_check_path %>
_check.html.erb
<div id = "notice">
</div>
check.js.erb
$("#notice").html('<p style="color: green;"><%= flash[:notice] %></p>').show().delay(5000).hide(0);
my_controller.rb
def check
notice = "NOTICE!"
respond_to do |format|
format.js do
flash[:notice] = notice
end
end
end
routes.rb
get 'app/check'
post 'app/check'
Try to the following
_check.html.erb
<% flash.each do |msg| %>
<%= msg.html_safe %>
<% end %>
check.js.erb
$("#notice").html('<%= escape_javascript(render("check")) %>');
my_controller.rb
Change this line
notice = "<p style='color: green;'>NOTICE!</p>"
Hope to help
You need to submit your form in JS format in order to render a JS type response!

Partial form is being rendered in the console but does not appear in the browser

I am trying to render a form in js.erb file when the condition is true.
Following is my create.js.erb file
<% if condition is true %>
$('#status-message').html("<%= escape_javascript(render 'form') %>")
<%else%>
#do something else
<%end%>
The create method in the controller is:
controller
def create
#code
respond_to do |format|
format.js # render app/views/phone_numbers/create.js.erb
end
end
Now when I checked in the console it is rendering the form
Rendered phone_numbers/_form.html.erb (4.2ms)
Rendered phone_numbers/create.js.erb (8.8ms)
Adding _form.html.erb as requested
<%= puts "Hello world"%>
<h3><%= Equipment.last.title %> </h3>
<h3><%= Equipment.last.price %> </h3>
But its not appearing on the browser. What am I missing ?
Resolved this in chat - the problem was that the #status-message element was inside a #status-box element that was hidden via css (with display: none;), so the fix was simply to add $('#status-box').show() to create.js.erb.

rails country select with state subregion in rails4

all. I'm following the carmen-rails documentation, though I'm using rails4, and I can't get the state subregion working when selecting a country. In fact, when leaving the subregion code in place I can't even navigate to the site. I get this error:
localhost:3000
Processing by OrdersController#new as HTML
Rendered orders/_subregion_select.html.erb (1.9ms)
Rendered orders/_form.html.erb (773.3ms)
Rendered orders/new.html.erb within layouts/application (775.8ms)
Completed 500 Internal Server Error in 784ms
ActionView::Template::Error (undefined method `downcase' for nil:NilClass):
1: <div id="order_state_wrapper">
2: <% parent_region ||= params[:parent_region] %>
3: <% country = Carmen::Country.coded(parent_region) %>
4:
5: <% if country.nil? %>
6: <em>Please select a country above</em>
app/views/orders/_subregion_select.html.erb:3:in `_app_views_orders__subregion_select_html_erb__937058573181156642_69893053026600'
app/views/orders/_form.html.erb:100:in `block in _app_views_orders__form_html_erb__3775537416523760398_69893046471120'
app/views/orders/_form.html.erb:1:in `_app_views_orders__form_html_erb__3775537416523760398_69893046471120'
app/views/orders/new.html.erb:6:in `_app_views_orders_new_html_erb__3931135682021831649_69893046299220'
Doesn't look like the (country, "US" in this case) paramater is being passed from the parent region because it's "nil". Any insight to get this working (I'm assuming with rails4) ?
app/views/orders/_form.html.erb
<div class="control-group">
<div class="field">
<%= f.label :country, 'Country' %>
<%= f.country_select :country, priority: %w(US CA), prompt: 'Please select a country' %>
</div>
<div class="field">
<%= f.label :state %><br />
<%= render partial: 'subregion_select', locals: {parent_region: f.object.country} %>
</div>
</div>
app/views/orders/_subregion_select.html.erb
<div id="order_state_wrapper">
<% parent_region ||= params[:parent_region] %>
<% country = Carmen::Country.coded(parent_region) %>
<% if country.nil? %>
<em>Please select a country above</em>
<% elsif country.subregions? %>
<%= subregion_select(:order, :state, parent_region) %>
<% else %>
<%= text_field(:order, :state) %>
<% end %>
</div>
app/assets/javascripts/orders.js.coffee
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$ ->
$('select#order_country').change (event) ->
select_wrapper = $('#order_state_wrapper')
$('select', select_wrapper).attr('disabled', true)
country = $(this).val()
url = "/orders/subregion_options?parent_region=#{country}"
select_wrapper.load(url)
config/routes.rb
get '/orders/subregion_options' => 'orders#subregion_options'
# rake routes
Prefix Verb URI Pattern Controller#Action
orders_subregion_options GET /orders/subregion_options(.:format) orders#subregion_options
and when browsing to the subregion route directly and specifying a country:
http://localhost:3000/orders/subregion_options?parent_region=%22US%22
Started GET "/orders/subregion_options?parent_region=%22US%22" for 192.168.122.1 at 2013-07-08 13:20:21 -0400
Processing by OrdersController#subregion_options as HTML
Parameters: {"parent_region"=>"\"US\""}
DEPRECATION WARNING: Relation#first with finder options is deprecated. Please build a scope and then call #first on it instead. (called from service at /usr/local/rvm/rubies/ruby-2.0.0-p195/lib/ruby/2.0.0/webrick/httpserver.rb:138)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered orders/_subregion_select.html.erb (0.2ms)
Completed 200 OK in 4ms (Views: 1.3ms | ActiveRecord: 0.2ms)
The gem carmen-rails isn't registered on http://ready4rails4.net/, on the github page it written
carmen-rails is a Rails 3 plugin that supplies two new form helper methods: country_select and subregion_select.
plus on travis-ci.org https://travis-ci.org/jim/carmen-rails all builds are done with rails 3.2.
I would say the gem isn't Rails 4 ready maybe.
You should open an issue on the github page.
After having looked at your comment I have checked out the fork you're using and excepted the branch name I didn't saw any Rails 4 related commits.
Having a look at the changelog file (https://github.com/freerunningtechnologies/carmen-rails/blob/master/CHANGELOG.md) make me thinking that the rails 4 compatibility isn't done yet, but maybe I'm wrong.
I got the same error on my Rails 3.2.15 application. I had to make one small change to the Carmen gem in order for it to work. Follow these instructions and you should be golden:
In terminal at your project root, use bundle open carmen to open the Carmen gem library.
Find the file lib/carmen/querying.rb.
Replace line 15 with the following:
code = code.try(:downcase) # Codes are all ASCII
I've submitted a pull request to the original author so this might get fixed soon in the master branch, but until then you can do the above or you can use my fork in your gemfile as follows:
gem 'carmen', github: 'joshuapinter/carmen'
Figured something that is causing of your error I also ran out.
<div id="order_state_code_wrapper">
<% parent_region ||= params[:parent_region] %>
<% unless parent_region.nil? %>
<% country = Carmen::Country.coded(parent_region) %>
<% end%>
<% if country.nil? %>
<em>Please select a country above</em>
<% elsif country.subregions? %>
<%= subregion_select(:order, :state_code, parent_region) %>
<% else %>
<%= text_field(:order, :state_code) %>
<% end %>
</div>
You need to add this to remove error
<% unless parent_region.nil? %>
<% country = Carmen::Country.coded(parent_region) %>
<% end%>
unless is necessary on page load first time parent_region is nil that time
and remove /orders from url and routes since it is not calling controller action subregion_options and using subregion_options as id
modified url and routes
url = "/subregion_options?parent_region=#{country}"
get '/subregion_options' => 'orders#subregion_options'

Carrierwave empty files - The file “MyDocument.pdf” could not be opened because it is empty

I am using Carrierwave to upload files. On my development machine running OS X 10.8 I am able to upload the file and download the file as expected. Tailing the development log I see:
Started GET "/resources/download_file/11" for 127.0.0.1 at 2013-03-24 06:29:33 -0400
Processing by ResourcesController#download_file as HTML
Parameters: {"id"=>"11"}
Resource Load (0.2ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "11"]]
Sent file /Users/scervera/rails_apps/mdn/public/uploads/resource/document/11/MyDocument.pdf (0.1ms)
Completed 200 OK in 2ms (ActiveRecord: 0.2ms)
After deploying with Capistrano onto my Ubuntu 12.04 server VM, I am able to upload the file (and verify it is physically on the server), however, when I click on the link to download the file I receive a message that says:
"The file “MyDocument.pdf” could not be opened because it is empty."
Tailing the production.log shows this:
Started GET "/resources/download_file/1" for 192.168.0.90 at 2013-03-24 06:31:12 -0400
Processing by ResourcesController#download_file as HTML
Parameters: {"id"=>"1"}
Sent file /var/mdnapp/releases/20130322184251/public/uploads/resource/document/1/MyDocument.pdf (0.1ms)
Completed 200 OK in 2ms (ActiveRecord: 0.1ms)
Note that this sql line is missing:
Resource Load (0.2ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ?
When I tried to open the file, it is indeed empty.
Also, I have tried adding the following to my deploy.rb, but while this is helpful, did not solve this particular problem:
set :shared_children, shared_children + %w{public/uploads}
Additional Details
I have a resources_controller with a method called download_file. See below:
def download_file
#resource = Resource.find(params[:id])
send_file(#resource.document.path,
:type => 'application/pdf',
:disposition => 'attachment',
:url_based_filename => true)
end
In my view I have a link tag that calls this method. See view code below:
<% if #resources.empty? %>
<p>There are no resources available at this time.</p>
<% else %>
<% #resources.each do |resource| %>
<div class="resource_wrap clearfix">
<h1><%= resource.title.html_safe %></h1><h2><%= resource.subtitle.html_safe %></h2>
<p><%= image_tag resource.image_url(:wallet).to_s %><%= resource.description.html_safe %></p>
<div id="attachments">
<% if resource.document? %>
<p>Get the resource:<%= link_to 'Download File', :action => 'download_file', :id => resource.id %></p>
<% end %>
<% if resource.video? %>
<p>Get the video:<%= link_to 'Download Video', :action => 'download_video', :id => resource.id %></p>
<% end %>
</div>
</div>
<% end %>
<% end %>
I'm running rails 3.2.11, ruby 1.9.3p194, carrierwave 0.8.0, rmagick 2.13.2
Please let me know if you need any additional details.
OK. I figured out the problem. I had to edit my config/environments/production.rb file and commented out the following line:
config.action_dispatch.x_sendfile_header = "X-Sendfile"
Spent a lot of hours researching this one. I hope someone else can benefit.

Refresh a div from link_to rails 3.1

I'm a newbye that is trying to do little things in Rails, at the moment I have created an app that build some links and I want to refresh the content of a Div when they are clicked.
In my application.html.erb I have the layout with the next head:
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
(I have read about change the second line for :defaults but if do that I get a 404 error defauls.js)
I have an index.html.erb that render a partial with this:
<%= render :partial => 'masvisitadas' %>
In my _masvisitadas.html.erb I have the code that generate the links:
<%= link_to solution.SolutionName, "/soluciones/despliega/" + solution.Id.to_s, :remote=>true %>
This generate the next html:
http://localhost:3000/soluciones/despliega/501D0000000QWp6IAG
In my controller I have the next def:
def despliega
respond_to do |format|
format.js {}
end
end
Finally I have created despliega.js.erb:
jQuery(function($) {
var html = "<%= escape_javascript(render('despliega')) %>";
$("#customTopLeft").prepend(html)
$("customTopLeft").html("<%= escape_javascript(render(:partial => 'despliega')) %>");
});
In the log of the web server when i click a link it seems all going well:
Started GET "/soluciones/despliega/501D0000000QXM0IAO" for 127.0.0.1 at 2012-08-
20 12:16:53 +0200
Processing by SolucionesController#despliega as JS
Parameters: {"id"=>"501D0000000QXM0IAO"}
Rendered soluciones/_despliega.html.erb (0.0ms)
Rendered soluciones/_despliega.html.erb (0.0ms)
Rendered soluciones/despliega.js.erb (15.6ms)
Completed 200 OK in 31ms (Views: 31.3ms | ActiveRecord: 0.0ms)
And in the firebug I can see the call with any error but nothing happends.
This is killing my head :) Thanks in advance for any help here.
Regards.
What's in _despliega.html.erb?
Try changing despliega.js.erb to this (and only this):
$('#customTopLeft').html("<%= escape_javascript(render :partial => 'despliega') %>");
Edit - oh, and make sure you have the jQuery libraries included ..

Resources