看一个选择Category或从text_field创建新Category的例子:
[code]
<!-- views/products/_form.rhtml -->
<p>
<label for="product_category_id">Category:</lable><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>
[/code]
我们修改product.rb,加一个before_save:
[code]
# models/product.rb
class Product < ActiveRecord::Base
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
end
[/code]
其中create_category是belongs_to :category自动创建的方法
[code]
<!-- views/products/_form.rhtml -->
<p>
<label for="product_category_id">Category:</lable><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>
[/code]
我们修改product.rb,加一个before_save:
[code]
# models/product.rb
class Product < ActiveRecord::Base
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
end
[/code]
其中create_category是belongs_to :category自动创建的方法