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

来源:百度文库 编辑:神马文学网 时间:2024/04/29 02:01:28
railscast第17集017_habtm_checkboxes的例解: rails demo -d mysqladmin -u root create demo_development ruby script/generate model productruby script/generate model category  ---------001_create_products.rbclass 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.rbclass 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中加入:

  
  <% for category in Category.find(:all) %>  
 

  
    <%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>  
    <%= category.name %>  
 
  
  <% end %>  

   在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