#57 Create Model Through Text Field

Let's say you provide a select menu for setting which category a given product belongs to, but you also want the option of creating a new category by typing the name in a text field. See a great way to do that in this episode.
<!-- views/products/_form.rhtml -->
<p>
  <label for="product_category_id">Category:</label><br />
  <%= f.collection_select :category_id, Category.find(:all), :id, :name, :prompt => "Select a Category" %>
  or create one:
  <%= f.text_field :new_category_name %>
</p>
# models/product.rb
belongs_to :category
attr_accessor :new_category_name
before_save :create_category_from_name

def create_category_from_name
  create_category(:name => new_category_name) unless new_category_name.blank?
end

你可能感兴趣的:(F#)