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.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
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.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
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>
<% 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] ||= []
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
if @product.update_attributes(params[:product])
flash[:notice] = 'Product was successfully updated.'
redirect_to :action => 'show', :id => @product
else
render :action => 'edit'
end
end
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/103515,如需转载请自行联系原作者