How to associate descendant models to a parent
I have the following models:
Account
has_many :libraries
Library
has_many :topics
belongs_to :account
Topic
has_many :functions
belongs_to :library
Function
has_one :example
belongs_to :topic
Example
belongs_to :function
I would like to be able to able to do things such as:
some_account.libraries
some_account.topics
some_account.functions
some_account.examples
In addition, I would like to be able to assign an account to a descendant, i.e
some_example.account = some_account
some_function.account = some_account
some_topic.account = some_account
some_library开发者_Python百科.account = some_account
To give some context: I am letting a user (Account) create each Library, Topic, Function, Example. record separately. Then a user is free to change how the records are associated: Change the topic of a Function, move a Topic to a different Library, add an example to a function, and so on.
To my understanding no matter what record is created, I would need to assign it to a user (account) so that I can have a list of each Model records that a user has created, as well as prevent other users from seeing stuff that doesn't belong to them
Although I might be overcomplicating, I really don't know :(
Thanks in advance.
Just put
belongs_to :account
on each entity a user can make... and add a foreign key, and
Account
has_many :libraries
has_many :topics
has_many :functions
has_many :examples
(Note: I use the hobo_fields gem to make migrations easier)
That way.. if they change which functions are in which topics etc.. you can't loose who created it.
If you want to make sure users cannot add their topics to someone else's library just put validation on the record to prevent it.
精彩评论