您确定 type 被允许作为控制器中的可访问参数吗
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' %>
而不是 :type
<%= 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();
}
});
});