原创作者: hideto   阅读:1414次   评论:1条   更新时间:2011-05-26    
看一个选择Category或从text_field创建新Category的例子:
<!-- 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>

我们修改product.rb,加一个before_save:
# 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

其中create_category是belongs_to :category自动创建的方法
评论 共 1 条 请登录后发表评论
1 楼 xu_ch 2009-03-11 15:09

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics