Hi I am trying to create a icon in my project which on click should download a file from public directory.
I dont get any error but still the download isn't happening
Please point out what I am missing. Thanks in advance
html.erb
<%= image_tag('down.png', :alt => 'Download file', :title => 'Download file', :id => 'download_sample_icon') %>
<% content_for (:jq) do %>
fetch_file_name = function(){
$.ajax({
url : "/file_uploads/download_import_sample",
data : { file_name: $('#file_upload_action').val() }
});
}
$(document).on("click", "#download_sample_icon", fetch_file_name);
file_uploads_controller.rb
def download_import_sample
file_name = params[:file_name] && params[:file_name].split(' ').map{|e| e.downcase}.join('_')+".xlsx"
send_file "#{Rails.root}/public/import_samples/"+"#{file_name}" if file_name.present?
end
Console output
Started GET "/file_uploads/download_import_sample?file_name=file+one" for 127.0.0.1 at 2017-08-01 13:22:22 +0530 (pid:2840)
Processing by FileUploadsController#download_import_sample as */* (pid:2840)
Parameters: {"file_name"=>"file one"} (pid:2840)
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 3446 LIMIT 1 (pid:2840)
Company Load (0.2ms) SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = 1060 LIMIT 1 (pid:2840)
Sent file /home/user/Project/base/public/import_samples/file_one.xlsx (0.1ms) (pid:2840)
Completed 200 OK in 120ms (pid:2840)
Try
def download_import_sample
excel_file = File.join(Rails.root, "public", "folder_in_public_directory")
fileName = params[:file_name] && params[:file_name].split(' ').map{|e| e.downcase}.join('_')+".xlsx"
send_file(File.join(excel_file, fileName))
end
Related
Following the hartle tutorial here: https://www.learnenough.com/action-cable-tutorial#sec-upgrading_to_action_cable
When I get to Step 4, adding ActionCable the chat messages are not transmitted and I get the error:
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ? [["LIMIT", 1]]
An unauthorized connection attempt was rejected
here are the relevant files:
room_channel.rb:
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
messages controller:
class MessagesController < ApplicationController
before_action :logged_in_user
before_action :get_messages
def index
end
def create
message = current_user.messages.build(message_params)
if message.save
ActionCable.server.broadcast 'room_channel',
message: render_message(message)
message.mentions.each do |mention|
ActionCable.server.broadcast "room_channel_user_# {mention.id}",
mention: true
end
end
end
private
def get_messages
#messages = Message.for_display
#message = current_user.messages.build
end
def message_params
params.require(:message).permit(:content)
end
def render_message(message)
render(partial: 'message', locals: { message: message })
end
end
room.coffee:
App.room = App.cable.subscriptions.create "RoomChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
# Called when there's incoming data on the websocket for this channel
alert data.content
routes.rb:
Rails.application.routes.draw do
root 'messages#index'
resources :users
resources :messages
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
mount ActionCable.server, at: '/cable'
end
The reference branch works fine on my machine, but I can't get my tutorial branch to use AC.
Update:
Skipping down to Section 5 of the tutorial, I added connection.rb, which had been blank in the tutorial's beginning repo as follows:
connection.rb:
module ApplicationCable
class Connection < ActionCable::Connection::Base
include SessionsHelper
identified_by :message_user
def connect
self.message_user = find_verified_user
end
private
def find_verified_user
if logged_in?
current_user
else
reject_unauthorized_connection
end
end
end
end
And broadcasting seems to work in one direction. I have two tabs open. but only one works to broadcast messages. In the other, the console shows this error:
Error: Existing connection must be closed before opening action_cable.self-17ebe4af84895fa064a951f57476799066237d7bb5dc4dc351a8b01cca19cce9.js:231:19
Connection.prototype.open
http://localhost:3000/assets/action_cable.self-17ebe4af84895fa064a951f57476799066237d7bb5dc4dc351a8b01cca19cce9.js:231:19
bind/<
http://localhost:3000/assets/action_cable.self-17ebe4af84895fa064a951f57476799066237d7bb5dc4dc351a8b01cca19cce9.js:201:60
In the logs, with the above connection.rb, the search for null user is gone, showing this:
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Registered connection (Z2lkOi8vY2hhdC1hcHAvVXNlci8x)
RoomChannel is transmitting the subscription confirmation
RoomChannel is streaming from room_channel
Started GET "/cable" for ::1 at 2018-12-29 08:04:31 -0500
Started GET "/cable/" [WebSocket] for ::1 at 2018-12-29 08:04:31 -0500
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
I created an ActiveAdmin user and I can no longer log on using any of my previous ActiveAdmin users nor can I create a new one. When I try, I get a 401 error. I have tried multiple times to manipulate the devise initializer and the model to no avail.
Using rails 5.2.1,activeadmin 1.3.1, activeadmin_addons 1.6.0, cancancan 2.2.0
active_admin_role 0.2.1
Processing by ActiveAdmin::Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Xyn9lV8tJQE9+Kii+LjFwiwrR4VKOXF8oACcQK4ui8Nb/9jkqDY8hfCHKEpX4/ftO3aKtdb0KJ9RXTq1TIbhpw==", "admin_user"=>{"login"=>"hodari#hiddengeniusproject.org", "password"=>"[FILTERED]", "remember_me"=>"1"}, "commit"=>"Submit"}
AdminUser Load (1.1ms) SELECT "admin_users".* FROM "admin_users" WHERE (lower(email) = 'hodari#hiddengeniusproject.org') ORDER BY "admin_users"."id" ASC LIMIT $1 [["LIMIT", 1]]
Completed 401 Unauthorized in 149ms (ActiveRecord: 1.9ms)
Processing by ActiveAdmin::Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"Xyn9lV8tJQE9+Kii+LjFwiwrR4VKOXF8oACcQK4ui8Nb/9jkqDY8hfCHKEp X4/ftO3aKtdb0KJ9RXTq1TIbhpw==", "admin_user"=>{"login"=>" ", "password"=>"
[FILTERED]", "remember_me"=>"1"}, "commit"=>"Submit"}
Rendering /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/sessions/new.html.erb within
layouts/active_admin_logged_out
Rendered /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/shared/_links.erb (1.6ms)
Rendered /Users/professortoure/.rvm/gems/ruby-2.4.1/gems/activeadmin-
1.3.1/app/views/active_admin/devise/sessions/new.html.erb within
layouts/active_admin_logged_out (51.6ms)
Completed 200 OK in 838ms (Views: 836.8ms | ActiveRecord: 0.0ms)
Here is my adminuser model
class AdminUser < ApplicationRecord
role_based_authorizable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable
attr_accessor :login
has_many :classrooms
protected
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
where(conditions).where(["lower(email) = :value", { :value => login
}]).first
end
end
and here is my devise.rb
Devise.setup do |config|
config.secret_key = ENV['devise_secret_key'] if Rails.env.production?
config.mailer_sender = 'Devise Omniauth
config.mailer = 'Devise::Mailer'
config.parent_mailer = 'ActionMailer::Base'
config.authentication_keys = [:login]
config.reset_password_keys = [:login]
config.strip_whitespace_keys = [:email, :username ]
config.params_authenticatable = true
config.http_authenticatable = false
config.paranoid = true
config.skip_session_storage = [:http_auth]
config.clean_up_csrf_token_on_authentication = true
config.reload_routes = true
config.stretches = Rails.env.test? ? 1 : 11
config.allow_unconfirmed_access_for = 364.days
config.confirm_within = 365.daysconfig.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 6..128
config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
config.unlock_strategy = :both
config.reset_password_within = 6.hours
Rails.application.config.app_middleware.use OmniAuth::Builder do
config.omniauth :google_oauth2,
Figaro.env.google_client_id,
Figaro.env.google_client_secret
#google_oauth2_options
{
scope: 'email, calendar',
prompt: 'select_account',
image_aspect_ratio: 'original',
name: 'google',
access_type: 'offline',
provider_ignores_state: true
}
end
end
I'm am not sure what else to include, I am still learning.
thank you
I just went back into my git repository to the last known working version and reset to there. Not sure what the problem was but my app is working again.
This is my first rails application. My task is to display, delete and update the records using .ajax(). I have displayed and deleted the records but i cant update the records i couldn't figure out what is going wrong. My controller code is
def update
#aj = Aj.find params[:id]
respond_to do |format|
if #aj.update(aj_params)
format.html { redirect_to #aj, notice: 'Aj was successfully updated.' }
format.json { render :show, status: :ok }
else
format.html { render :edit }
format.json { render json: #aj.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_aj
#aj = Aj.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def aj_params
params.require(:aj).permit(:name, :title, :content)
end
end
and my route file is
match '/ajs/' => 'ajs#update', :via => :patch
match '/ajs/:id/edit' => 'ajs#edit', :via => :get
and could able to edit my form after changing the data when i click on update button it given the error
Couldn't find Aj without an ID
# Use callbacks to share common setup or constraints between actions.
def set_aj
#aj = Aj.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
edited:
I have javascript code in html itself
$(document).on("click", ".edit", function(){
var id = $(this).data('id');
alert("edit"+id)
$.ajax({
url: "ajs/"+id+"/edit",
type: "get",
data: id,
//dataType: "html",
success: function(data) {
$("#mybox").html(data);
$(document).on("click", "#subid", function(){
alert(id);
$.ajax({
url: "ajs/"+id,
type: "patch",
success: function(data) {
alert("success");
},
error: function(){
alert("error")
}
}); // show ajax() closed
});//show click() closed
},
error: function(){
alert("error")
}
}); // show ajax() closed
});//show click() closed
I have added a id for the update button and id name is "subid " when i click on that button i am passing my id am getting id of the row. when i used ajax for passing that id now i am getting another error:
No route matches [PATCH] "/ajs"
Rails.root: /home/liplw015/Documents/rails/ajaxjs
In my console:
Started PATCH "/ajs/134" for 127.0.0.1 at 2014-07-14 09:38:09 +0530
Processing by AjsController#update as */*
Parameters: {"id"=>"134"}
Aj Load (0.4ms) SELECT "ajs".* FROM "ajs" WHERE "ajs"."id" = ? LIMIT 1 [["id", 134]]
Completed 400 Bad Request in 4ms
ActionController::ParameterMissing (param is missing or the value is empty: aj):
app/controllers/ajs_controller.rb:98:in `aj_params'
app/controllers/ajs_controller.rb:69:in `block in update'
app/controllers/ajs_controller.rb:68:in `update'
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack- 4.1.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.9ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.3ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.9ms)
Rendered /home/liplw015/.rvm/gems/ruby-2.1.2/gems/actionpack-4.1.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb (22.5ms)
Started PATCH "/ajs" for 127.0.0.1 at 2014-07-14 09:38:10 +0530
ActionController::RoutingError (No route matches [PATCH] "/ajs"):
actionpack (4.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
your route is wrong, include id in route
match '/ajs/:id' => 'ajs#update', :via => :patch
I'm following Railscast #199 to allow my web app to be viewed in a mobile browser. It works great, except when I try to access information in a tabbed interface using UJS in the mobile version. Clicking on the tabs works in the web app, but on the mobile side I get a 406 error. (I tried this after setting the User Agent as iPhone in Safari. I also tested on iOS Simulator and my iPhone. Neither time loaded anything.)
Below is some code for one of the tabs. Can anyone can help me target what is going on? Here is my code.
Here's the profile_about action in profiles_controller.rb:
def profile_about
#profile = Profile.find(params[:id])
respond_to do |format|
format.js { render :layout => nil }
end
end
In my profiles/show.mobile.erb (this is the exact same code as in profiles/show.html.erb):
<div id="tabs">
<ul id="infoContainer">
<li><%= link_to "Cred", profile_cred_profile_path, :class=> 'active', :remote => true %></li>
<li><%= link_to "About", profile_about_profile_path, :class=> 'inactive', :remote => true %></li>
</ul>
<div id="tabs-1">
<%= render :partial => 'profile_cred' %>
</div>
</div><!-- end tabs -->
(NOTE: I have a file for profiles/_profile_about.html.erb and profiles/_profile_about.mobile.erb.)
Here is my profiles/profile_about.js.erb:
$("#tabs-1").html("<%= escape_javascript(render(:partial => 'profile_about'))%>");
My Heroku logs showing the 406:
2012-03-08T03:02:55+00:00 app[web.1]: Started GET "/profiles/1/profile_about" for 98.218.231.113 at 2012-03-08 03:02:55 +0000
2012-03-08T03:02:55+00:00 heroku[router]: GET myapp.com/profiles/1/profile_about dyno=web.1 queue=0 wait=0ms service=14ms status=406 bytes=1
2012-03-08T03:02:55+00:00 app[web.1]: Processing by ProfilesController#profile_about as JS
2012-03-08T03:02:55+00:00 app[web.1]: Parameters: {"id"=>"1"}
2012-03-08T03:02:55+00:00 app[web.1]: Completed 406 Not Acceptable in 3ms
2012-03-08T03:02:55+00:00 heroku[nginx]: 98.218.231.113 - - [08/Mar/2012:03:02:55 +0000] "GET /profiles/1/profile_about HTTP/1.1" 406 1 "http://myapp.com/profiles/1" "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3" myapp.com
From running tail -f logs/development.log:
Started GET "/profiles/1/profile_about" for 127.0.0.1 at Wed Mar 07 22:35:36 -0500 2012
Processing by ProfilesController#profile_about as JS
Parameters: {"id"=>"1"}
PK and serial sequence (5.4ms) SELECT attr.attname, seq.relname
FROM pg_class seq,
pg_attribute attr,
pg_depend dep,
pg_namespace name,
pg_constraint cons
WHERE seq.oid = dep.objid
AND seq.relkind = 'S'
AND attr.attrelid = dep.refobjid
AND attr.attnum = dep.refobjsubid
AND attr.attrelid = cons.conrelid
AND attr.attnum = cons.conkey[1]
AND cons.contype = 'p'
AND dep.refobjid = '"goals_profiles"'::regclass
PK and custom sequence (2.5ms) SELECT attr.attname,
CASE
WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
substr(split_part(def.adsrc, '''', 2),
strpos(split_part(def.adsrc, '''', 2), '.')+1)
ELSE split_part(def.adsrc, '''', 2)
END
FROM pg_class t
JOIN pg_attribute attr ON (t.oid = attrelid)
JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
WHERE t.oid = '"goals_profiles"'::regclass
AND cons.contype = 'p'
AND def.adsrc ~* 'nextval'
Profile Load (1.3ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" = '1' LIMIT 1
Completed 406 Not Acceptable in 30ms
There's a few bugs in your code, maybe it's just stackoverflow formatting here but the inner quotes should be ' instead of " , like this:
$("#tabs-1").html("<%= escape_javascript(render(:partial => 'profile_about'))%>");
And this line is casuing your error:
format.mobile.js {render :layout => nil}
This is impossible because the request can only have a single mime type. "mobile" or "js", not both. If you are requesting the "profile_about" action from javascript, then you must respond back to it with js. "format.mobile" should only be used to render a "profile_about.mobile" template.
Hopefully that's at least a step in the right direction for you.
Probably don't fully answer your question but I was having the 406 status problem, because I've been deploying my app to Phonegap!
It basically happened because the request type didn't match any of the Rails responders in the action.
it was like:
respond_to do |format|
format.json {
render( json: (#parishes) )
}
end
Since I only used it to responde to JSON I changed and it now works:
render( json:(#parishes) )
A more complete way to deal with this is to figure exactly what responder is being asked for that request, or default to something you know to work
Turns out this was due to a lacking check for an xhr request in the prepare_for_mobile method. I found the answer in another question. So the below prepare_for_mobile method allows the JS to work:
def prepare_for_mobile
session[:mobile_param] = params[:mobile] if params[:mobile]
request.format = :mobile if mobile_device? && !request.xhr?
end
This is the error I see:
Timeout::Error in Devise/registrationsController#create
execution expired
This is what my development.rb looks like:
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# 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 webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't 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
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
config.action_mailer.default_url_options = { :host => 'localhost:3000' } #Make sure to set 'host' to domain name in production.
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
end
I check my logs, this is what I see, once I click the 'Submit' button on the Registration form:
Started GET "/users/register" for 127.0.0.1 at 2011-02-11 19:19:23 -0500
Processing by Devise::RegistrationsController#new as HTML
nil
Rendered devise/shared/_links.erb (2.4ms)
Rendered devise/registrations/new.html.erb within layouts/application (98.1ms)
Completed 200 OK in 160ms (Views: 109.0ms | ActiveRecord: 0.0ms)
Started POST "/users" for 127.0.0.1 at 2011-02-11 19:20:03 -0500
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qWs4IOH3L+GT/Sld8rZRlhXi8JM0pe0NtWG4Tn9XRIU=", "user"=>{"username"=>"marcamillion", "f_name"=>"marc", "l_name"=>"gayle", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"marc#amillion.com"}, "commit"=>"Register"}
nil
WARNING: Can't mass-assign protected attributes: f_name, l_name
User Load (0.2ms) SELECT "users"."id" FROM "users" WHERE (LOWER("users"."email") = LOWER('marc#amillion.com')) LIMIT 1
User Load (0.1ms) SELECT "users"."id" FROM "users" WHERE (LOWER("users"."username") = LOWER('marcamillion')) LIMIT 1
CACHE (0.0ms) SELECT "users"."id" FROM "users" WHERE (LOWER("users"."email") = LOWER('marc#amillion.com')) LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE ("users"."confirmation_token" = 'DCo8QgqWQfnYWq20n5Uf') LIMIT 1
AREL (31.0ms) INSERT INTO "users" ("email", "encrypted_password", "password_salt", "reset_password_token", "remember_token", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "username", "f_name", "l_name", "created_at", "updated_at", "invitation_token", "invitation_sent_at", "plan_id", "current_state", "confirmation_token", "confirmed_at", "confirmation_sent_at") VALUES ('marc#amillion.com', '$2a$10$55hQTGZpUKbeT5n30/eyau96jf5zzd18t19jV/Y4g8Urou/El4vKy', '$2a$10$55hQTGZpUKbeT5n30/eyau', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'marcamillion', NULL, NULL, '2011-02-12 00:20:03.699983', '2011-02-12 00:20:03.699983', NULL, NULL, NULL, NULL, 'DCo8QgqWQfnYWq20n5Uf', NULL, '2011-02-12 00:20:03.699855')
Rendered devise/mailer/confirmation_instructions.html.erb (1.0ms)
Sent mail to marc#amillion.com (30009ms)
Date: Fri, 11 Feb 2011 19:20:03 -0500
From: no-reply#myapp.com
To: marc#amillion.com
Message-ID: <4d55d233bfe9f_bd4880443b3c837ee#MyMacBook-Pro.local.mail>
Subject: Confirmation instructions
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<p>Welcome marc#amillion.com!</p>
<p>You can confirm your account through the link below:</p>
<p>Confirm my account</p>
Completed in 30349ms
Timeout::Error (execution expired):
I am assuming you don't have an SMTP server running locally. Unless you really need the mail to be delivered in development, then you can remove this stuff and it should not error on you:
config.action_mailer.default_url_options = { :host => 'localhost:3000' } #Make sure to set 'host' to domain name in production.
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
If you do want mail delivered in dev, then google setting up smtp server. Or you can even use something like gmail as an SMTP server