0

Using the simple form gem for Ruby on Rails, I have a form that looks like this:

<%= simple_form_for(article, html: {class: 'form-vertical'}) do |f| %>
  ...
  <div class="field">
    <%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category"} %>
    <%= f.collection_select :subcategory_id, Subcategory.all, :id, :name, {prompt: "Choose a subcategory"} %>
    <%= f.input :title %>
    <%= f.input :content, input_html: { rows: 20 }%>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Is there a way to base the options in the subcategory input on the selection in the category input? What I mean is, if I had a category "food", then I would be able to pick a subcategory "apple", but not "table". Would this be possible?



Category model:

class Category < ApplicationRecord
  has_many :articles
  has_many :subcategories
end

Subcategory model:

class Subcategory < ApplicationRecord
  belongs_to :category
end
Alex
  • 49
  • 9

1 Answers1

0

What you want to happen cannot be done with rails alone. Rails performs actions on page updates. What you need is a JavaScript library like jQuery to change the content of your page after an on-page event like .change()

$("#article_category_id").change(function() {
  # Code to update content of subcategory
}

Examples can be found on this site like here: Use jQuery to change a second select list based on the first select list option

Community
  • 1
  • 1
Okomikeruko
  • 1,123
  • 10
  • 22
  • Yes, that's what I was thinking too. I just have no idea how I would integrate jQuery with Rails in this case -- JavaScript would have to be able to access the database containing the categories/subcategories. – Alex Jul 12 '16 at 17:42
  • Here's an answer that uses HAML and CoffeeScript http://stackoverflow.com/questions/34867232/populate-rails-form-with-data-based-on-the-previous-field-select – Okomikeruko Jul 12 '16 at 17:48