【发布时间】:2013-02-07 08:11:52
【问题描述】:
我已经编辑了我的请求,希望更清楚。我需要根据之前的选择框动态渲染一个部分。
REQUEST 属于 PRODUCT
产品属于类别
CATEGORY 有很多产品
产品有很多请求
用户点击表单:create_request.html.erb
用户选择一个类别,然后填充产品选择列表(如 Railscast 88 - 动态选择框)
我现在需要的是根据选择的产品呈现不同的部分表单。我很讨厌 jquery。
create_request.html.erb:
<%= javascript_include_tag "dynamic_products.js" %>
<% form_for :request, :url => {:controller => :requests, :action => :create_request, :id => params[:id]} do |f| %>
<label>Select Category:</label>
<%= select( "request", "category_id", Category.find( :all).collect { |c| [c.name, c.id] })%></br>
<div id="product_field">
<label>Select Product</label>
<%= select( "request", "product_id", Product.find( :all).collect { |p| [p.name, p.id] })%></br>
</div>
#### and here is where I need help:
#### if request.product_id = 1, render partial _form1
#### if request.product_id = 2, render partial _form2
<button type="submit">Submit</button>
<% end %>
dynamic_products.js.erb:
var products = new Array();
<% for product in @products -%>
products.push(new Array(<%= product.category_id %>, '<%=h product.name %>', <%= product.id %>, <%= product.active %>));
products.sort()
<% end -%>
function categorySelected() {
category_id = $('request_category_id').getValue();
options = $('request_product_id').options;
options.length = 1;
products.each(function(product) {
if (product[0] == category_id && product[3] == 1) {
options[options.length] = new Option(product[1], product[2]);
}
});
if (options.length == 1) {
$('product_field').hide();
} else {
$('product_field').show();
}
}
document.observe('dom:loaded', function() {
categorySelected();
$('request_category_id').observe('change', categorySelected);
});
【问题讨论】:
-
您需要使用Ajax,在产品/服务选择框的'onChange'事件上触发,将选中的值传递给Ajax,然后部分渲染表单。
-
这正是我需要做的。你能帮我用一个骨架方法让我开始吗?真的很感激
-
我需要更多关于请求/类别/产品之间关系的信息(谁属于谁);以及可能应该如何更新 select_box(刷新属于所选类别的产品列表?)
-
请求有很多类别和产品。产品属于类别。类别属于请求。用户选择类别,然后填充产品选择列表(这已经有效)。然后我需要的是根据所选产品显示不同的形式。
-
我已经编辑了我的原始帖子,希望更清晰。提前致谢。
标签: ruby-on-rails