分享

通过多选框实现多对多关系的数据输入

 Joshua 2009-03-24
railscast第17集017_habtm_checkboxes的例解:
 
rails demo -d mysql
admin -u root create demo_development
 
ruby script/generate model product
ruby script/generate model category
 
 
---------001_create_products.rb
class CreateProducts < ActiveRecord::Migration
  def self.up
    create_table :products do |t|
      t.column :name, :string
      t.column :price, :decimal
    end
   
  end
  def self.down
    drop_table :products
  end
end
--------002_create_categories.rb
class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.column :name, :string
    end
   
    create_table :categories_products , :id=>false do |t|
      t.column :product_id, :integer
      t.column :category_id, :integer
    end
  end
  def self.down
    drop_table :categories
  end
end
运行
rake db:migrate
 
ruby script/generate product admin -f
 
在_form.rhtml中加入:
<p>  
  <% for category in Category.find(:all) %>  
  <div>  
    <%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>  
    <%= category.name %>  
  </div>  
  <% end %>  
</p> 
 
在admin_controller.rb里的update这个方法里加入:
def update
    params[:product][:category_ids] ||= []  
    @product = Product.find(params[:id])
    if @product.update_attributes(params[:product])
      flash[:notice] = 'Product was successfully updated.'
      redirect_to :action => 'show', :id => @product
    else
      render :action => 'edit'
    end
  end

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多