[Rails] ActiveRecord modelling problem

  • Thread starter Dmitry V. Sabanin
  • Start date
D

Dmitry V. Sabanin

Hi!

I'm designing CMS for a corporate use with Rails and I have a problem with
implementing some of my ideas about content structure.
In my plans, I want to have a model called Folder, to which all the relevant
data will be linked. Any folder can be a parent for any other Folder, so they
should create a hierarchical structure like this:
+ Folder 1
`- Folder 2
`- Folder 3
`- Folder 4
`- Folder 5
+ Folder 6
`- Folder 7
.....and so on
And now the problem: how can I do this with ActiveRecord?
I want to follow KISS for now, so `folders` table is like:
+ id
+ parent_id
+ name
+ description
However, I fear that there's no way to do 'has_many :folders' inside Folder
model, because it's not in AR's design(probably there'll be "name-guessing"
issues or someth like that). Any ideas are very, very appreciated!

Thanks in advance,
 
A

Andreas Schwarz

Dmitry said:
I want to follow KISS for now, so `folders` table is like:
+ id
+ parent_id
+ name
+ description
However, I fear that there's no way to do 'has_many :folders' inside Folder
model, because it's not in AR's design(probably there'll be "name-guessing"
issues or someth like that). Any ideas are very, very appreciated!

This is no problem with ActiveRecord:

belongs_to :parent, :class_name => 'Folder', :foreign_key => 'folder_id'
has_many :children, :class_name => 'Folder', :foreign_key => 'folder_id'
 
D

Dmitry V. Sabanin

This is no problem with ActiveRecord:

belongs_to :parent, :class_name => 'Folder', :foreign_key => 'folder_id'
has_many :children, :class_name => 'Folder', :foreign_key => 'folder_id'

Super, but I'm not sure how to use that now. How can I add Folders to a
Folder? I've tried folder.folders << another_folder and folder.childrens <<
another_folder but with no success. Btw, big thanks for your help and quick
reply!
 
D

Dmitry V. Sabanin

Super, but I'm not sure how to use that now. How can I add Folders to a
Folder? I've tried folder.folders << another_folder and folder.childrens <<
another_folder but with no success.
Answering my own question with Andreas help from #rubyonrails, you have to use
Folder#children<< to add folder.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top