简体   繁体   中英

How do I set a model object as its own attribute in Rails?

I want to build a tree using one model/table. I have a model named Node and an attribute root . For the root node, I want to set it as the root .

I could do this:

n = Node.new root:0
# save new query
n.save
n.root = n.id
# save update query
n.save

but I want to do this all in one query. How do I do this?

Sounds like you want this gem: https://github.com/rails/acts_as_tree

  root      = Category.create("name" => "root")
  child1    = root.children.create("name" => "child1")
  subchild1 = child1.children.create("name" => "subchild1")

Basically your Node model will have a parent_id attribute. When it's nil it means that Node is the root.

You can't do it in a single database operation because the id doesn't get assigned until the save occurs and the id isn't available until after that point. You can use a factory (eg FactoryGirl) to do it in a single factory operation using the factory mechanism's "after save" hook.

Maybe something like this using after_commit callback:

after_commit :set_root, :on => :create
def set_root
   self.update_attribute(:root_id, self.id) if root_id == 0
end

可能只能通过回调,因为在获取对象之前必须先保存对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM