打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
SQLAlchemy详细教程
Rails ---> routes.rb 详解
SQLAlchemy数据建模过程的改进
EasyTime - Ruby学习笔记 | Agile Web Development with Rails 翻译(十四)
成功动态显示某表字段列表、选择字段、设置字段属性
MySQL 8.0 数据字典表
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服