【发布时间】:2015-05-18 05:30:44
【问题描述】:
I am trying to implement ajax in my rails app, A job category dropdown is present based on the selection the page shows jobs.Here i am facing the issue is when a category job is selected all the jobs are shown by default.
class JobsController < ApplicationController
before_action :find_job, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!,except:[:index]
def index
if params[:jobcategory].blank?
@jobs = Job.where(active: true).order("created_at DESC")
else
@jobcategory_id = Jobcategory.find_by(name: params[:jobcategory]).id
@jobs =Job.where(jobcategory_id: @jobcategory_id).order("created_at DESC")
end
respond_to do |format|
format.html # show.html.erb
format.json #{ render json: "testing" }
format.js # show.js.erb
end
end
dropdown.js
$(function(){
$("#divNewNotifications").on('click', function(){
$.getScript(this.href);
return false;
});
});
_testing.html.haml
- @jobs.each do |job|
%div{class: "col-md-3"}
%div{class: "thumbnail"}
%div{class: "caption"}
%h3= link_to job.title, job
%h4= job.company
%h6= job.location
index.js.erb
$(function(){
$("#testing").html("<%= j (render("testing")) %>");
});
index.html.haml
%hearder
%nav.navbar.navbar-job
.container{class: "text-center"}
%div{class: "btn-group"}
%ul.dropdown
%a.btn.dropdown-toggle.btn-job{"data-toggle" => "dropdown","role" => "button"}
Jobs
%span{class: "caret",id: "dropdown_title"}
%ul.dropdown-menu{id: "divNewNotifications"}
%li= link_to "All Creative Jobs", jobs_path
- Jobcategory.all.each do |jobcategory|
%li= link_to jobcategory.name, jobs_path(jobcategory: jobcategory.name),remote: true
%body
%div{id:"testing"}
= render 'testing'
Rails.application.routes.draw do
get 'errors/filenot_found'
get 'errors/unprocessable'
get 'errors/internal_server_error'
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users
resources :jobs do
collection do
get 'all'
end
end
root 'jobs#index'
get "/404" => "errors#file_not_found"
get "/422" => "errors#unprocessable"
get "/500" => "errors#internal_server_error"
end
【问题讨论】:
-
您需要显示“#divNewNotifications”链接所在的实际视图以及您的路线。此外,您可能还想了解 Ajax 通常是如何完成的。通过传递 JSON 数据,而不是脚本。
-
@papirtiger 嗨,谢谢,我忘记在 index.html.haml 中添加它了……我已经更新了。我们是否必须在 routes.db 中为 Ajax 设置路由? ,还有任何想法如何解决这个问题?我是 Rails 和 Ajax 的新手。
-
添加您的
routes.rb。默认情况下,Rails 路由将响应任何请求内容类型 - 所以不,您不需要为 ajax 设置特殊路由。 -
@papirtiger 好的,我已经添加了 routes.rb .... 我一直在努力解决这个问题,你能帮我解决这个问题吗?
标签: javascript ruby-on-rails ajax ruby-on-rails-4 ajaxform