gpt4 book ai didi

javascript - RJS:Ajaxified select_tag

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:09 24 4
gpt4 key购买 nike

因为我在 last question 上没有得到预期的答案我会尽量简化和缩小我的问题:

How can I build a dropdown-menu that uses AJAX (no submit-button) to call the show action of a certain controller?

给出了以下内容:

Model-AssociationCategories HABTM Projects,因此下拉菜单包含所有类别名称。

应在其中实现下拉菜单的部分 View 。下拉菜单下方是应根据下拉菜单中的选择更改的项目列表:

   <!-- placeholder for AJAX dropdown menu -->

<!-- list of projects related to categories chosen by the select tag -->
<ul class="projects">
<% @projects.each do |_project| %>
<li>
<%= link_to(_project.name, _project) %>
</li>
<% end %>
</ul>

具有应调用的显示操作的类别 Controller :

class CategoriesController < ApplicationController
def show
# params[:id] should be the choice the user made in the dropdown menu
@category = Category.find(params[:id])
@projects = @category.projects.find(:all)

respond_to do |format|
format.html # show.html.erb
format.js # needed for ajax response?
end
end

def index
@projects = Category.find(params[:id]).projects.find(:all)
@category = @project.categories.first

respond_to do |format|
format.html # index.html.erb
end
end
end

在 Categories Controller 中调用 show-action 的路由:

category GET    /categories/:id    {:controller=>"categories", :action=>"show"}

您将如何实现?非常感谢任何帮助!

最佳答案

这个怎么样:

<% form_for :category, :url => { :action => "show" } do |f| %>
<%= select_tag :id, options_from_collection_for_select(Category.find(:all), :id, :name),
{ :onchange => "this.form.submit();"} %>
<% end %>

这将调用传统的 html 调用,因此它将刷新整个页面(并响应 format.html)。

然后 Controller 会根据提交的[:id]找到类别

@category = Category.find(params[:id])

关于javascript - RJS:Ajaxified select_tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/579855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com