link_to remote: true redirecting to HTML - ruby-on-rails

At the /tags page I have a link with remote: true. It should be a link to an ajax request. But there are two requests, as JS and as HTML.
<%= link_to 'New', new_tag_path, class: "btn btn-outline btn-primary", remote: true %>
INFO -- : Started GET "/tags/new" for 192.168.18.236 at 2018-06-13 11:44:18 -0300
INFO -- : Processing by TagsController#new as JS
INFO -- : Rendered tags/_form.html.erb (41.0ms)
INFO -- : Rendered tags/_modal.html.erb (41.5ms)
INFO -- : Rendered tags/new.js.erb (49.2ms)
INFO -- : Completed 200 OK in 63ms (Views: 50.3ms | ActiveRecord: 2.2ms)
INFO -- : Started GET "/tags/new" for 192.168.18.236 at 2018-06-13 11:44:18 -0300
INFO -- : Processing by TagsController#new as HTML
INFO -- : Completed 500 Internal Server Error in 14ms (ActiveRecord: 1.9ms)
FATAL -- :
ActionView::MissingTemplate (Missing template tags/new, application/new with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
If I provide a new.html.erb, this MissingTemplate error is over, but the page is redirected to new.html.
What could be wrong with that request or that link?
Edit The controller code
class TagsController < ApplicationController
before_action :set_tag, only: [:show, :edit, :update, :destroy, :fix_correct_name]
before_action :set_tags, only: [:new, :edit]
# GET /tags/new
def new
#tag = Tag.new
end
# GET /tags/1/edit
def edit
end
# POST /tags
def create
#tag = Tag.new(tag_params)
respond_to do |format|
if #tag.save
format.html { redirect_to action: "index", notice: 'Tag adicionada.' }
else
format.html { render :new }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tag
#tag = Tag.find(params[:id])
end
def set_tags
#tags = Tag.all.pluck(:name, :id)
end
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params.fetch(:tag, {}).permit(:name, :parent_id, :tag_name, :parent_name, :no_parent)
end
end

In your new action, you’ll need a response_to to handle the ajax call
def new
#tag = Tag.new
respond_to { |format| format.js }
end
Also, you’ll need a new.js.erb file and a _new.html.erb partial to handle the response and update the view.
Inside your new.js.erb, you will have to render the view with something like this
$(“div-id-name”).html(“<%= j render partial: “new” %>”)
And your new partial will simply hold your form (or whatever is it you wanna render)

I made it work now, only replacing require jquery_ujs by require rails-ujs to application.js and adding rails-ujs gem.

Related

How to download an uploaded stored file from the database in rails?

Im trying to implement a download functionality to an uploaded pdf file in my app. For some reason the record can not be found? If I check the GET Request I see that it tries to use the url ending "/resumes/download.5". 5 is the record id from the stored file. What am I missing? How can I debug issues like that in the future? Byebug did not work this time for some reason.
views/resumes/show.html.erb
<%= link_to "Download", resume_download_path(#resume) %>
resumes_controller.rb
class ResumesController < ApplicationController
around_filter :catch_not_found
before_action :find_resume, only: [ :show, :edit, :update, :destroy, :download ]
before_action :authenticate_user!
def show
end
def new
if #resume = current_user.resume
redirect_to #resume
else
#resume = Resume.new
end
end
def create
#resume = current_user.build_resume(resume_params)
if #resume.save
redirect_to #resume
else
render :new
end
end
def edit
end
def update
if #resume.update resume_params
redirect_to #resume, notice: "Your resume was successfully saved!"
else
render 'edit'
end
end
def destroy
#resume.destroy
redirect_to new_resume_path, notice: "Your resume was successfully deleted!"
end
def download
send_data #resume, type: "application/pdf", disposition: "attachment"
end
private
def resume_params
params.require(:resume).permit( :user_id, :download_file, :remove_download_file)
end
def find_resume
#resume = Resume.find(params[:id])
end
def catch_not_found
yield
rescue ActiveRecord::RecordNotFound
redirect_to(root_url, :notice => 'Record not found')
end
end
routes.rb
Rails.application.routes.draw do
devise_for :users
root 'welcomes#index'
resources :resumes
get "resumes/download", as: "resume_download"
get '*path' => redirect('/')
end
When clicking on the download link:
Started GET "/resumes/download.5" for 77.8.13.5 at 2017-08-23 21:22:14 +0000
Cannot render console from 77.8.13.5! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ResumesController#show as
Parameters: {"id"=>"download"}
Resume Load (0.2ms) SELECT "resumes".* FROM "resumes" WHERE "resumes"."id" = ? LIMIT 1 [["id", 0]]
Redirected to https://rails-tutorial-martinbortowski.c9.io/
Completed 302 Found in 3ms (ActiveRecord: 0.2ms)
Started GET "/" for 77.8.13.5 at 2017-08-23 21:22:15 +0000
Cannot render console from 77.8.13.5! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by WelcomesController#index as HTML
Rendered welcomes/index.html.erb within layouts/application (0.2ms)
Completed 200 OK in 39ms (Views: 38.4ms | ActiveRecord: 0.0ms)
resources :resumes do
get :download, on: :member
end
Will give you an idiomatically correct REST route:
resumes/:id/download
Change your link to:
<%= link_to "Download", download_resume_path(#resume), "data-turbolinks" => false %>
See Rails Routing from the Outside In - Adding More RESTful Actions.
You download link seems to be wrong.
change in your routes.rb
get "resumes/download", as: "resume_download"
to
controller :resumes do
get "resumes/download/:id" => :show, as: :resume_download
end
views/resumes/show.html.erb
change your link
<%= link_to "Download", resume_download_path(#resume) %>
to
<%= link_to "Download", resume_download_path(id: #resume) %>

ActionController::ParameterMissing (param is missing or the value is empty: item):

I have programmed an android app, which can take profile pictures from a user. Now I want to upload these profile picture to my Ruby on Rail server. However the upload doesn't work. I receive the Error message:
app/controllers/items_controller.rb:55:in `item_params'
app/controllers/items_controller.rb:21:in `create'
Started POST "/items" for 192.168.3.7 at 2016-09-11 01:12:21 +0900
Processing by ItemsController#create as HTML
Parameters: {"image"=>#<ActionDispatch::Http::UploadedFile:0x5737110 #tempfile=#<Tempfile:C:/Users/Clemens/AppData/Local/Temp/RackMultipart20160911-2
8624-1vjbftr.jpg>, #original_filename="IMG_20160911_010525.jpg", #content_type="application/octet-stream", #headers="Content-Disposition: form-data; na
me=\"image\"; filename=\"IMG_20160911_010525.jpg\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n">}
Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms)
ActionController::ParameterMissing (param is missing or the value is empty: item):
app/controllers/items_controller.rb:55:in `item_params'
app/controllers/items_controller.rb:21:in `create'
Why does this not work? How should my item_params be defined? Here is my items_controller.rb
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
# GET /items
# GET /items.json
def index
#items = Item.all
end
# GET /items/1
# GET /items/1.json
def show
send_data(item.file_contents,
type: #item.content_type,
filename: #item.filename)
end
# POST /items
# POST /items.json
def create
#item = Item.new(item_params)
if #item.save
render :show, status: :created, location: #item
else
render json: #item.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /items/1
# PATCH/PUT /items/1.json
def update
if #item.update(item_params)
render :show, status: :ok, location: #item
else
render json: #item.errors, status: :unprocessable_entity
end
end
# DELETE /items/1
# DELETE /items/1.json
def destroy
#item.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
#item = Item.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def item_params
#######################params.require(:item).permit(:name, :description, :picture)
params.permit(:picture)
end
end
UPDATE: I renamed my image from android app and called it "item". Now the parameter error disappears. However a new error arises:
app/controllers/items_controller.rb:24:in `create'
Started POST "/items" for 192.168.3.7 at 2016-09-11 10:25:26 +0900
Processing by ItemsController#create as HTML
Parameters: {"item"=>#<ActionDispatch::Http::UploadedFile:0x53b1d30 #tempfile=#<Tempfile:C:/Users/Clemens/AppData/Local/Temp/RackMultipart20160911-3144-anlpp6.jpg>, #original_filename="IMG_20160911_100920.jpg", #co
ntent_type="application/octet-stream", #headers="Content-Disposition: form-data; name=\"item\"; filename=\"IMG_20160911_100920.jpg\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n"
>}
Unpermitted parameter: item
(0.0ms) BEGIN
SQL (31.2ms) INSERT INTO `items` (`created_at`, `updated_at`) VALUES ('2016-09-11 01:25:26', '2016-09-11 01:25:26')
(0.0ms) COMMIT
Completed 500 Internal Server Error in 62ms (ActiveRecord: 31.2ms)
ActionView::MissingTemplate (Missing template items/show, application/show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}. Searched in:
* "C:/Benutzer/Clemens/RubymineProjects/rails-api-fileupload-tutorial-carrierwave-single/app/views"
):
app/controllers/items_controller.rb:24:in `create'
Any idea why I get this error? I put in views following line both in views\application\show.json.jbuilder and in views\items\show.json.jbuilder:
json.extract! #item, :locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]
However I still get the same error.
What is happening is that this line:
params.require(:item).permit(:name, :description, :picture)
will raise an exception if you do not have an item in your params. When you are sending to your create action, apparently you do not have an item. I am also assuming that when you saw this error you didn't have that line commented.

Accessing a method in rails controller via button/link

I was trying to follow the solution on this thread - Rails 3 link or button that executes action in controller
I defined :update_question in my routes.rb file:
resources :surveys do
put :update_question, :on => :member
end
and in my controller:
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
before_action :set_question
# GET /surveys
# GET /surveys.json
def index
#surveys = Survey.all
end
# GET /surveys/1
# GET /surveys/1.json
def show
end
def survey
#survey = Survey.find(params[:survey_id])
end
# GET /surveys/new
def new
#survey = Survey.new
end
# GET /surveys/1/edit
def edit
end
def update_question
flash[:alert] = "getting there man"
end
And listed the link here in the html:
<%= link_to "Next Question", update_question_survey_path(#survey), {:method => :put} %>
However when I click the link I get this error:
Template is missing
Missing template surveys/update_question, application/update_question with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}.
Which seems to elude that it's looking for a view - but really I just want it to run the method in my survey controller and update the question that's being displayed. Perhaps I'm going about this the wrong way, any help/suggestions is much appreciated!
That's because the action is correctly reached, but then Rails tries to render something. By default, it will look for a view file with the same name of the action.
You should do something like this:
def update_question
set_survey
# do stuff
flash[:alert] = "getting there man"
redirect_to survey_path(#survey)
end

issue on render :update do

My session controller
class SessionsController < ApplicationController
skip_before_filter :is_loggedin?, :only => [:new, :create]
def new
render :action => "new", :layout => false
end
def create
render :update do |page|
if !params[:email].blank? && !params[:password].blank?
if user = User.authenticate(params[:email], params[:password])
if user == "unuser"
page.alert("Your username and/or password was incorrect.")
elsif !user.account_id.blank?
if params[:remember_me]
cookies.permanent[:user_id] = user.id
else
cookies[:user_id]=user.id
end
user.update_attributes(:last_login => Time.now, :is_online => true)
if user.user_type=="mentor"
page.redirect_to home_mentors_path(:account_id =>user.account_id)
else
page.redirect_to home_students_path(:account_id =>user.account_id)
end
else
page.alert("You have not confirmed the activation link yet. Please check your registered email ")
end
else
page << "jQuery('#login_error').html('Invalid user/password');"
end
else
page.alert("You can't leave this empty.")
end
end
My sessions/_form.htm is like this:
<%= form_tag sessions_path, :remote => true, :method =>"post" do %>
<div id="login-modal" class="shadow" style="display: block; z-index: 4000;">
<div class="login_bar_top">
<div class="login_bar_left"></div>
<div class="login_bar_mid">User Login</div>
<div class="login_bar_right"></div>
</div>
I have lot of controllers with code render :update do, now it will take lot of time to review all, with respond_to do. I tried by installing prototype-rails gem also. Not solved.
Error I am facing is:
Started POST "/sessions" for 127.0.0.1 at 2013-12-10 13:59:50 +0530
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"42cE1Mx5gXzmZAbSwgSnxbbygYLH4x81lbPjkCDKAOs=", "email"=>"mentor#gmail.com", "password"=>"[FILTERED]"}
Completed 500 Internal Server Error in 2ms
ActionView::MissingTemplate (Missing template sessions/update, application/update with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee, :rjs]}. Searched in:
* "/home/prz/project/techzoorails/techzoo3/app/views"
):
app/controllers/sessions_controller.rb:9:in `create'
Previous it was working fine. Is there any solution by keeping render :update code. I am using rails 3.0.9 with ruby 1.9.3p392.

rails 4 template missing error in render in ajax

I have the following ajax function
$.ajax({
url: '/sub_categories/sub_cat',
data: 'sub_cat=45',
success: function() {
alert('success');
}
})
Here is my controller
require 'json'
class SubCategoriesController < ApplicationController
def show
end
def sub_cat
#sub_categories = SubCategory.where(category_id: params[:cat_id])
html = render_to_string 'sub_categories/sub_cat'
response_html true,html
end
end
My application controller
def response_html status,html
respond_to do |format|
format.json {render json: {
status: status,
html: html,
}
}
format.html
end
end
I have json file in sub_categories/sub_cat.json.erb
When I run getting error as
ActionView::MissingTemplate at /sub_categories/sub_cat.json
Missing template sub_categories/show, application/show with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in:
* "/home/editmehere/Documents/site/name/app/views"
My route.rb has
resources :sub_categories do
get 'sub_cat', on: :collection
end
Why I am getting error like this and how can I solve it. Can anyone help me to solve it.
I'm guessing you're trying to keep your application dry, but why don't you just use this in your SubCategoriesController:
class SubCategoriesController < ApplicationController
def sub_cat
#sub_categories = SubCategory.where(category_id: params[:cat_id])
respond_to do |format|
format.json
format.html
end
end
end
This will allow you to call sub_cat.json.erb without having to pass the status var, or pre-render the HTML. This is just convention, so apologies if it's not what you need. I see a lot of people on here overcomplicate things, when simplicity would work much better
Ajax
Also, I believe you've got a problem with your ajax data var:
data: 'sub_cat=45',
should be
data: {sub_cat: "45"},

Resources