Formulário Rails 4: exibição condicional de campos com base na seleção de botões de opção

Primeiro, desculpe-me se esta pergunta for idiota, estou apenas começando a entender o Rails, e o Javascript e o jQuery são um mundo totalmente novo para mim.

Encontrei as seguintes perguntas semelhantes, mas simplesmente não entendo como elas podem se aplicar à minha situação:

Mostrar / ocultar div se a caixa de seleção estiver selecionadaVerificar campos de entrada ocultos com base no botão de opção selecionadoMostrar campos de formulário com base na seleção dos botões de opção

Dito isto, aqui está a minha pergunta.

No meu aplicativo Rails 4, tenho o seguinte formulário Rails (eu souNÃO usando o formulário simples):

<div class="calendar_details">
  <%= f.label :target_relationship %>
  <%= radio_button_tag(:target_relationship, "B2C", :checked => true, :onclick=>"showMe('calendar_details_b2c')", {:class => "radio_button_target_relationship_b2C"}) %>
  <%= label_tag(:target_relationship, "B2C") %>
  <%= radio_button_tag(:target_relationship, "B2B", :onclick=>"showMe('calendar_details_b2b')", {:class => "radio_button_target_relationship_b2b"}) %>
  <%= label_tag(:target_relationship, "B2B") %>
</div>

<div class="calendar_details">
  <%= f.label :target_country %><%= f.country_select :target_country, ["United States"] %>
</div>

<div id="calendar_details_b2c">

  <div class="calendar_details">
  <%= f.label :target_gender %><%= radio_button_tag(:target_gender, "Female") %><%= label_tag(:target_relationship, "Female") %><%= radio_button_tag(:target_gender, "Male") %><%= label_tag(:target_relationship, "Male") %><%= radio_button_tag(:target_gender, "Both", :checked => true) %><%= label_tag(:target_relationship, "Both") %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_age_lower_limit %><%= f.select :target_age_lower_limit, (0..99) %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_age_upper_limit %><%= f.select :target_age_upper_limit, (0..99) %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_household_income_lower_limit %><%= f.select :target_household_income_lower_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_household_income_upper_limit %><%= f.select :target_household_income_upper_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
  </div>

</div>

<div id="calendar_details_b2b">

  <div class="calendar_details">
    <%= f.label :target_company_size %><%= f.select :target_company_size, ['Self-employed', '1-10 employees', '11-50 employees', '51-200 employees', '201-500 employees', '501-1,000 employees', '1,001-5,000 employees', '5,001-10,000 employees', 'More than 10,000 employees'] %>
  </div>
  <div class="calendar_details">
    <%= f.label :target_industry %><%= f.select :target_industry, ['Art & Entertainment', 'Autos & Vehicles', 'Beauty & Fitness', 'Books & Litterature', 'Business & Industrial', 'Computer & Electronics', 'Finance', 'Food & Drinks', 'Games', 'Hobbies & Leisure', 'Home & Garden', 'Internet & Telecom', 'Jobs & Education', 'Law & Government', 'News', 'Online Communities', 'People & Society', 'Pets & Animals', 'Real Estate', 'Science', 'Shopping', 'Sports', 'Travel']  %>
  </div>

</div>

Com base no que os usuários verificam no primeiro botão de opção ("B2C" ou "B2B"), eu gostaria de exibir ocalendar_details_b2c div, ou ocalendar_details_b2b div.

Eu entendo que vou precisar esconder ambosdivs, para implementar alguma forma de condição, verificando qual botão de opção está marcado e, finalmente, exibir o botão direitodiv.

Como você pode ver, tentei adicionar umonclick opção e algumas classes específicas para os meus botões de opção, mas estou paralisado: não sei como criar a função js correta e não sei onde incluí-la (no.html.erb arquivo do formulário, no cabeçalho do aplicativo, noapplication.js Arquivo?).

—————

ATUALIZAR: conforme resposta de Ziv Galili, eis o que tenho agora:

Noapp/assets/javascript/custom/calendars.js:

$(document).ready(function() {
    $('input[type=radio][name=calendar').change(function () {
      // first: hide all the divs
      $('#calendar_details_b2c').css("display","none");
      $('#calendar_details_b2b').css("display","none");

      // then get the div ID to show (I stored it in the "value" of the radio button)
      var fieldToShow = $(this).val();
      // now use jQuery selector and change the display setting of that field
      $("#" + fieldToShow).css("display","block");
    });
});

Noapplication.js, Eu adicionei//= require_tree ./custom para levar o código acima em consideração no meu aplicativo.

Na exibição em que meu formulário está (Calendars#New agora):

<div class="calendar_details">
    <%= f.label :target_relationship, "Business relationship" %>
    <%= f.radio_button :target_relationship, "calendar_details_b2c", :checked => true %>
    <%= f.label(:target_relationship, "B2C") %>
    <%= f.radio_button :target_relationship, "calendar_details_b2b", :checked => false %>
    <%= f.label(:target_relationship, "B2B") %>
  </div>

  <div class="calendar_details">
    <%= f.label :target_country, "Country" %><%= f.country_select :target_country, ["United States"] %>
  </div>

  <div id="calendar_details_b2c">

    <div class="calendar_details">
    <%= f.label :target_gender, "Gender" %><%= radio_button_tag(:target_gender, "Female") %><%= label_tag(:target_relationship, "Female") %><%= radio_button_tag(:target_gender, "Male") %><%= label_tag(:target_relationship, "Male") %><%= radio_button_tag(:target_gender, "Both", :checked => true) %><%= label_tag(:target_relationship, "Both") %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_age_lower_limit, "Age / Lower limit" %><%= f.select :target_age_lower_limit, (0..99) %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_age_upper_limit, "Age / Upper limit" %><%= f.select :target_age_upper_limit, (0..99) %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_household_income_lower_limit, "Household income / Lower limit" %><%= f.select :target_household_income_lower_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_household_income_upper_limit, "Household income / Upper limit" %><%= f.select :target_household_income_upper_limit, ['Less than $10,000', '$10,000', '$20,000', '$30,000', '$40,000', '$50,000', '$60,000', '$70,000', '$80,000', '$90,000', '$100,000', '$110,000', '$120,000', '$130,000', '$140,000', '$150,000', '$160,000', '$170,000', '$180,000', '$190,000', '$190,000', '$200,000', 'More than $200,000'] %>
    </div>

  </div>

  <div id="calendar_details_b2b">

    <div class="calendar_details">
      <%= f.label :target_company_size, "Company size" %><%= f.select :target_company_size, ['Self-employed', '1-10 employees', '11-50 employees', '51-200 employees', '201-500 employees', '501-1,000 employees', '1,001-5,000 employees', '5,001-10,000 employees', 'More than 10,000 employees'] %>
    </div>
    <div class="calendar_details">
      <%= f.label :target_industry, "Industry" %><%= f.select :target_industry, ['Art & Entertainment', 'Autos & Vehicles', 'Beauty & Fitness', 'Books & Litterature', 'Business & Industrial', 'Computer & Electronics', 'Finance', 'Food & Drinks', 'Games', 'Hobbies & Leisure', 'Home & Garden', 'Internet & Telecom', 'Jobs & Education', 'Law & Government', 'News', 'Online Communities', 'People & Society', 'Pets & Animals', 'Real Estate', 'Science', 'Shopping', 'Sports', 'Travel']  %>
    </div>

  </div>

No entanto, não consigo fazer isso funcionar: quando visito oCalendars#New Na visualização, vejo os botões de opção para selecionar B2C ou B2B, mas qualquer que seja o botão selecionado, nada será exibido abaixo (nem a seção B2C nem a seção B2B).

o que estou perdendo?

—————

ATUALIZAÇÃO 2: Então, atualizei meu código como o novo comentário de Ziv Galili, ou seja: prestando atenção no nome do grupo de botões, que na verdade écalendar[target_relationship].

Quando fiz isso e tentei ir ao meu ponto de vista, recebi umaexecJS::RuntimeError, o que me fez perceber que estávamos usando JavaScript puro, enquanto meu aplicativo Rails parece estar usando CoffeeScript.

Então eu apagueiapp/assets/javascript/custom/calendars.js, converteu o código de Ziv Galili em CoffeeScript e o adicionou em app / assets / javascript / calendars.coffee:

$('input[type=radio][name=calendar[target_relationship]]').change ->
  # first: hide all the divs
  $('#calendar_details_b2c').css 'display', 'none'
  $('#calendar_details_b2b').css 'display', 'none'
  # then get the div ID to show (i stored it in the "value" of the radio button
  fieldToShow = $(this).val()
  # now use jQuery selector and change the display setting of that field
  $('#' + fieldToShow).css 'display', 'block'
  return

Eu também substitui//= require_tree ./custom com//= require_tree . para garantir que todo o meu.coffee arquivos foram carregados atravésapplication.js.

Apesar de todas essas atualizações de código, ainda não recebo o resultado esperado: nenhuma dasdivs são exibidos nas minhas visualizações:

Devo estar sentindo falta de algo realmente óbvio, mas não consigo descobrir o que é.

Qualquer ideia?

—————

Qualquer tipo de ajuda seria muito apreciada.

questionAnswers(3)

yourAnswerToTheQuestion