使用 Ajax 将项目动态添加到 Ruby On Rails 中的选择列表
我已经为此查看了一大堆解决方案,也许我只是很笨,但我无法让任何东西发挥作用。这些是我试图在产品/新视图中结合在一起的两个选择,这将允许用户选择产品类别,然后限制子类别列表:
<p>
<%= f.label :category_id %>:
<%= f.select("category", Category.find(:all).collect {|c|[c.name, c.id]})%>
</p>
<p>
<%= f.label :subcategory_id %>:
<%= f.select("subcategory", Subcategory.find(:all).collect {|s|[s.name, s.id]})%>
</p>
我的子类别控制器中有一个函数可以从数据库获取信息:
def get_subcategories
@subcategories = Subcategory.find_by_category_id(:all)
end
但我不知道如何将它连接在一起,而且看起来在 RoR 中应该很容易。
I have looked at a whole bunch of solutions for this and maybe I am just dense, but I can't get anything to work. These are the two selects I am trying to tie together in a product/new view that will allow the user to select a category of product and then constrain the subcategory listing:
<p>
<%= f.label :category_id %>:
<%= f.select("category", Category.find(:all).collect {|c|[c.name, c.id]})%>
</p>
<p>
<%= f.label :subcategory_id %>:
<%= f.select("subcategory", Subcategory.find(:all).collect {|s|[s.name, s.id]})%>
</p>
I have a function in my subcategory controller to get the information from the database:
def get_subcategories
@subcategories = Subcategory.find_by_category_id(:all)
end
But I can't figure out how to wire it together, and it seems like it should be easy in RoR.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,这并不完全是微不足道的,但只要付出一点努力就可以实现。基本方法是:
get_subcategories
方法在控制器操作内例如,在 JQuery 中,您可以将其与以下方法结合起来
.change()
在选择列表上设置处理程序.triggerEvent('change')
将导致加载后触发的事件(如果需要)$.getJSON()
可用于获取和解析 AJAX 响应.remove()
和.append ()
可用于清除子类别选择并用结果更新Well it's not completely trivial but it is achievable with a little effort. The basic approach would be:
get_subcategories
method within a controller actionFor example, in JQuery you could put this together with the following methods
.change()
sets up the handler on the select list.triggerEvent('change')
would cause the event to fire after load (if you need that)$.getJSON()
can be used to fetch and parse the AJAX response.remove()
and.append()
can be used to clear and update the subcategory select with the result