I am building a website that is basically a small Content Management System. (in the sense that the user will be able to dynamicaly change most content of the site)
In my rails app I have two models, a Category and a Subcategory. A Category has many Subcategories, and a Subcategory belongs to a Category.
Each subcategory has a position field, which dictates where it is displayed under the category.
When creating a subcategory by form, I want the user to have the option to select the category from a list of all categories in the database (Which I have working fine). I then want the position field (a dropdown box) to update based on what positions are currently available within that category.
My current idea to track the available position for subcategory in my Application Controller is:
def subcategory_count(subcategory)
category = subcategory.category
@count = category.subcategories.count
end
I then add +1 to @count
so it gives me the available positions, +1. (If anyone has a better way of doing this, please let me know.)
I am currently following Ryan Bates' railscasts 88 revised which is dynamic select menus revised. Here is what my form looks like right now.
<%= form_for(@subcategory) do |f| %>
<p>
<%= f.label(:name) %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label(:category_id) %>
<%= f.collection_select :category_id, Category.order(:position), :id, :name, include_blank: true %>
</p>
<p>
<%= f.label :position, "Position" %>
<%= f.grouped_collection_select :position, Category.order(:position), :subcategories, :name, :position, :position%>
</p>
<p>
<%= f.submit("Submit") %>
</p>
<% end %>
The problem with this code is that I need it to display as an int so I can add +1 to it, otherwise when there are no subcategories in the database it just shows blank and doesn't allow me to pick the "1" position.
So, I need to find a way to update the field to show the available positions in the category, but I don't know how to do that exactly. Any help will be greatly appreciated.
14: <%= f.label :position, "Position" %> 15: <%= f.grouped_collection_select :position, Category.order(:position), :subcategories_with_placeholder, :name, :position, :position%> 16:
17:18:
– ruevaughn Feb 12 '12 at 02:24