1

我想要根据您选择的出版物类型显示字段的表单。我已经使用单表继承(根据这个[链接] http://blog.thirst.co/post/14885390861/rails-single-table-inheritance)来创建发布模型(基本模型)和子类(book_chapter,book_whole 、会议文章、期刊文章)。出版物模型的字段如下:类型、作者、标题、年份、出版物、卷、期、页、关键字、摘要、出版商、出版地、编辑、系列标题、系列卷、系列问题、ISSN、isbn、区域、url、doi。

因此,根据将要选择的类型(例如 book_chapter),我希望拥有特定的出版物字段。

I handled to create dropdown list with types, but when select the type and create publications the Type record do not saved on database. 这是类型下拉列表的代码

  <%= 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>
4

1 回答 1

1

您确定 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();
    }
  });
});
于 2013-08-25T14:44:10.107 回答