Rails 3 nested resources with users (Devise) structure
I'm having general structural issues with Rails 3 and the new routes.rb is getting me a bit confused. Thanks for any help or guidance.
I have a forum application with nested resources. There are sections, topics, and replies. The routes.rb structure looks like this:
resources :sections do
resources :topics do
resources :replies
end
end
My section.rb:
has_many :topics
has_many :replies, :through => :topics
My topic.rb:
belongs_to :section
has_many :replies
My reply.rb:
belongs_to :topic
And this is working wonderfully. Now here's where I'm confused.
I added a user controller using Devise, and have a working username login/logout system. I'm trying to connect the 'current_user' with replies and topics. I think I have a good idea on how to fix the models, but I'm开发者_如何转开发 very confused with what to do in the routes.rb file.
For user.rb, I believe I need to add "has_many :topics" and "has_many :replies, :through => :topics". And then In my topics I need to add "belongs_to :user". I believe reply.rb remains the same?
As for the routes.rb I'm kind of stumped. If I edit the routes and add users to it, I would get a path like sectionid/username/topicid/ but I don't necessarily need to store a username in a route like that. So do I nest user in-between sections and topics or can I leave user out of the routes.rb file.
You can leave the users out of the path. Just include the devise_for :users on top of your routes without including it in your resources block.
A user has many topics and has many replies. Both topics and replies belong to a user.
There are more changes in your controllers needed. You need to add a before_filter to check if users are authenticated and in addition changes in most of your controller methods to check if users are not only authenticated but also authorized, e.g. for an edit lookup you do current_user.replies.... . You can read more on that here (my own page): http://www.communityguides.eu/articles/4.
精彩评论