我正在使用select_tag
和onchange
。我需要调用一个辅助方法并将所选项的值作为参数传递:
这是我的帮助方法的样子
def find_template(temp)
"Hello #{temp}!"
end
我需要做的是使用javascript进行用户选择,并将其传递给find_template
。如果我传递字符串而不是模板,它可以正常工作,即<% @header = find_template("option_1") %>
但是当我使用var template
时,我收到以下错误:
undefined local variable or method `template' for ...
这是我的erb
<% content_for :javascript do %>
<script>
function template() {
var e = document.getElementById("category");
var template = e.options[e.selectedIndex].text;
<% @header = find_template(template) %>
}
</script>
<% end %>
<%= select_tag(:category, options_for_select(
Blah::TYPES.map {|k, v| [v['name'], k] }),
{onChange: 'template()'}) %>
<div id="template-overview">
<table>
<tr>
<% @header.each do |column| %>
<th class="<%= cycle('even', 'odd') -%>">
<%= column %>
</th>
<% end %>
</tr>
</table>
</div>
答案 0 :(得分:1)
解决了:正确的做法是使用ajax:
你的page.erb 中的
<% content_for :javascript do %>
<script>
$(document).ready(function(){
$("#category").change(function(){
var temp_name = $('#category').val();
$.ajax({
url: "/YOUR_PATH/"+temp_name,
dataType: "html",
type: "GET",
data: {ANY_DATA: VALUES},
success: function(data){
jQuery("#template_overview").html(data);
}
});
});
});
</script>
<% end %>
<div id="template_overview">
</div>
有一部分填充你的div
在控制器中:
def display_template
.
.
.
.
render partial: '/PATH/template_overview', header: @header
end
当然还有路线
get 'controller/display_template/:temp_id' => 'controller#display_template'