1、自关联
例如:category类有经济和科普两个对象,经济下又有国内经济和国外经济两个对象,此时可利用自关联,通过一个parent_id来识别子类和父类之间的关系
model层的category.rb
class Category < ActiveRecord::Base
belongs_to:parent,
:class_name => 'Category' #指明模型名
has_many :children, #固定写法,切记切记
:class_name => 'Category', #指明模型名
:foreign_key => 'parent_id', #指明关联id
:dependent => :destroy #删除父节点时删除子节点
db/migrate层的category.rb
t.integer :parent_id
c1 = Category.new
c1.save #(id=1)
c2 = Category.new
c2.save #(id=2)
c1.children = c2
c1.save
此时,在此c2所对应的行中的parent_id=1
2、自关联中的named_scope写法(类名直接调用)
named_scope:sub_categories, :conditions =>"#{Category.table_name}.parent_id isnull", :order =>"#{Category.table_name}.title desc" do
def sub
all:include => [:children],:conditions => "childrens_categories.id isnull"
end
end
3、批量插入
insert into tablename select .. #将select的结果插入tablename中
update tablename set 字段=(select....) #用select的结果对tablename的字段进行更新
4、layout的选择顺序
方法内-> 类内定义->类默认 ->application_controller.rb