In a thread on the ActiveScaffold Google Group, I worked out the basics of hiding fields based on the value selected in a SELECT drop-down. However I am now stuck on a similar but more complicated version.
I have the following models in a Rails application:
class Sale < ActiveRecord::Base
belongs_to :product
validates_numericality_of :price_sold
validates_numericality_of :delivery_cost
end
class Product < ActiveRecord::Base
belongs_to :product_type
has_many :sales
end
class ProductType < ActiveRecord::Base
has_many :products
validates_presence_of :free_delivery #A boolean field
end
Example products: Nokia 6210, Apple iPhone, Apple iPod, Creative Zen and Canon 400D.
Example product types: Phone, MP3 Player and Camera.
Some Product Types have free delivery (e.g. MP3 Players and Phones), so I have a boolean field on Product Type to identify this.
Users of the app log sales by selecting a product from a drop-down and filling in price_sold and delivery_cost.
My ActiveScaffold for Sales currently works; I see a drop-down of products and I can enter the price_sold and delivery_cost. However, I now need to customise it so the delivery_cost field is hidden if the selected product is a product type that has free delivery. The problem is that the user selects a Product, but I need to somehow check the free_delivery flag on the associated Product Type.
Any help on how I can go about this?
Maybe there is a way to make an Ajax call to check the Product Type of the select Product?
Another idea might be to manaully build the SELECT dropdown myself, and instead of the values being the productid, they are a combination of the productid and the associated free_delivery flag. So instead of the normal:
<select class="product-input">
<option value="6">Nokia 6210</option>
<option value="5">Apple iPhone</option>
<option value="3">Apple iPod</option>
<option value="2">Creative Zen</option>
<option value="1">Canon 400D</option>
</select>
I have:
<select class="product-input">
<option value="6_true">Nokia 6210</option>
<option value="5_true">Apple iPhone</option>
<option value="3_true">Apple iPod</option>
<option value="2_true">Creative Zen</option>
<option value="1_false">Canon 400D</option>
</select>
Then hopefully I could have some JavaScript fire when the product is selected which picks out the true/false from the value and show/hides the delivery_cost field as appropriate.
I guess I'd also need to do something with ActiveScaffold so that on submitting of the form the '_false' bit gets stripped off and the productid can get saved correct in the database.