看一个选择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自动创建的方法
本文介绍如何在Rails应用中实现从表单输入动态创建Category。通过在产品模型中定义before_save回调并使用attr_accessor来传递新的Category名称,可以实现在保存产品时如果指定了新的Category名称则自动创建该Category。
333

被折叠的 条评论
为什么被折叠?



