我想要一个根据您选择的出版物类型显示字段的表单。我使用单表继承(根据此[链接] http://blog.thirst.co/post/14885390861/rails-single-table-inheritance )来创建发布模型(基本模型)和子类(book_chapter、book_whole、conference_article、journal_article)。出版物模型的字段如下:类型、作者、标题、年份、出版物、卷、期、页、关键字、摘要、出版商、出版地点、编辑、系列标题、系列卷、系列发行、issn、isbn、区域、url、doi。
因此,根据将要选择的类型(例如 book_chapter),我想要具有特定的出版物字段。
我处理了创建带有类型的下拉列表,但是当选择类型并创建发布时,类型记录不会保存在数据库中。这是类型下拉列表的代码 列表
<%= f.label :type, :class => 'control-label' %>
<div class="controls">
<%= f.collection_select :type, Publication.order(:type), :id, :type, include_blank: true, :class => 'text_field' %>
</div>
</div>
最佳答案
您确定类型被允许作为 Controller 中的可访问参数
def publication_params
params.require(:publication).permit(:type)
end
您确定选择中的选项值正确吗?
为什么你的collection_select包含:id
<%= f.collection_select :type, Publication.order(:type), :id, :type, include_blank: true, :class => 'text_field' %>
而不是:类型
<%= f.collection_select :type, Publication.order(:type), :type, :type, include_blank: true, :class => 'text_field' %>
<小时/>
关于你的第二个问题,答案将依赖于 JavaScript/客户端实现。 使用 jQuery 你可以实现这样的东西
# JS ($=jQuery)
# assuming your type select has id='type_select'
# assuming your fields inside your form have class 'field'
$('#type_select').change(function(event){
current_type = $(e.target).val();
$(e.target).parents('form').children('.field').each(function(el,i){
if($.inArray($(el).attr('id'), form_fields_for(current_type)){
$(el).show();
}else{
$(el).hide();
}
});
});
var form_fields_for= function(type){
{ book_chapter: [field1_id, field2_id, field3_id, field4_id],
book_whole: [field1_id, field2_id],
conference_article: [field1_id],
journal_article: [field1_id, field2_id, field3_id, field4_id, field5_id]
}[type];
};
<小时/>
另一个解决方案是为每种类型的每个字段设置特定的类:
如果我们采用与上面相同的假设,则 Rails 将显示如下形式:
# pseudocode (html form)
form
field1 class='book_chapter book_whole conference_article journal_article'
field2 class='book_chapter book_whole journal_article'
field3 class='book_chapter journal_article'
...
然后您将隐藏或显示这些特定的类
# JS ($=jQuery)
$('#type_select').change(function(event){
current_type = $(e.target).val();
$('.' + current_type).show();
$(e.target).parents('form').children('.field').each(function(el,i){
if(!$(el).hasClass(current_type)){
$(el).hide();
}
});
});
关于javascript - 如果模型是基于 Ruby on Rails 4 上的单表继承创建的,如何制作下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18430123/