我的路线如下所示:
resources :projects do
resources :tasks
end
这将为您提供如下 URL:URL/projects/14/tasks/3
模型定义:
project has_many :tasks
task belongs_to :project
现在,当用户单击任务链接时,我将通过项目显示 View 中的远程=> true 链接将tasks#show 加载到div 中。这工作正常。
#tasks/show.js.erb
$('#task_content').html("<%= j render(partial: 'tasks/single', locals: { t: @task }) %>");
<小时/>
#tasks/_single.html.erb
<%= t.content %>
问题是我希望用户能够访问 URL/projects/14/tasks/3 并将任务自动加载到项目 View 上的 div 中。
基本上,我需要找到一种方法来拥有 URL/projects/14/tasks/3
实际渲染URL/projects/14
,并调用 jquery $('a#task_<%= task.id %>').click()
我似乎不知道如何让 View 识别这种行为。有人能指出我正确的方向吗?
谢谢!!!
编辑
#TasksController
def show
@task = Task.find(params[:id])
respond_to do |format|
format.js
end
end
#ProjectsController
def show
@project = Project.find(params[:id])
respond_to do |format|
format.html # show.html.erb
end
end
Projects#show 有两个主要元素:
- ID 为 task_<%= task.id %> 的链接
- 任务所在的div 内容应加载到 (div#task_content)
最佳答案
Basically, I need to find a way to have URL/projects/14/tasks/3 actually render URL/projects/14, and call a jquery $('a#task_<%= task.id %>').click()
您可以测试任务是否通过标准 HTTP 调用(非 AJAX)到达,并重定向到项目的 URL,传入参数以在加载时自动加载任务。由于您的默认情况使用 js
格式,因此更简单 - 您只需测试 html
格式即可:
#TasksController
def show
@task = Task.find(params[:id])
respond_to do |format|
format.html { redirect_to project_path(@task.project_id, :load_task_id => @task.id) }
format.js
end
end
# somewhere in /projects/show partial
<% if params[:load_task_id] %>
<script type="text/javascript">
$(function(){
$('a#task_<%= params[:load_task_id] %>').click()
});
</script>
<% end %>
关于jquery - 通过ajax(rails)加载嵌套资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14124655/