I have a model class 'Market' which has many products:
class Market < ActiveRecord::Base
has_many :products
end
Product model:
class Product < ActiveRecord::Base
belongs_to :market
end
In my views markets/new.html.haml and markets/edit.html.haml I would like to have the feature that, a new/edit market is in开发者_开发技巧 a form, and inside this form, I have a "Add Product" button, when user press this button one row will be added in the form like this(each row is a instance of Product and each input field is a attribute of Product(name,price,category)), in HTML code:
<div>
<input type=text name="name" size=10 value="Name">
<input type=text name="price" size=10 value="Price">
<input type=text name="category" size=10 value="category">
<div>
<div>
<input type=text name=z3 size=10>
<input type=text name=z3 size=10>
<input type=text name=z3 size=10>
<div>
...When "Add product" button pressed, a new row of product input fields (div block) is added
<br>
<input type="submit" name="Add" value="Add product">
How to implement this "dynamically adding a product row" feature in a "Market" form??
In haml view file:
=form_for :market do |form|
...
=fields_for "product" market.product do |field|
=fields.text_field :name
=fields.text_field :price
=fields.text_field :category
/...When "Add product" button pressed, a new row of product input fields is added
=field.submit "Add product"
form.submit "Save"
How to implement if I use this haml file for the new/edit market view?
WHat you need is a nested_attributes for. It's a bit of a long read, but here's the link to a railscast:
http://railscasts.com/episodes/75-complex-forms-part-3
This is the updated railscast for rails 3:
http://railscasts.com/episodes/196-nested-model-form-part-1 thats in 2 parts :)
If you want to dive into the code immediately: https://github.com/ryanb/railscasts-episodes/tree/master/episode-196
精彩评论