Projects have users.
Users have expenses.
I have a screen for the currently signed in user to add new expenses, my controller forces the user key based on current_user.
Now I am needing to allow users to work within a particular project, and enter their expenses for that project all at once, basically “enter” a project-expense screen, to limit the scope of the expenses shown in that screen by the project they selected.
(Similar to the way basecamp makes you pick a project you work on)
I do want to use this view for other things, and would like to make it as DRY as possible.
Was just wondering, what is the proper way to have a user select a project, and then persist that choice through their use of my existing expenses screen.
EDIT – I would like to be able to pick a project, and then have all the functionality on the expenses page pass along that project through to the controller methods.
So I could end up with /project/45/expenses …. etc
Thanks!
class Project < ActiveRecord::Base
attr_accessible :name, :active
has_many :expenses, foreign_key: :project_id
end
class Expense < ActiveRecord::Base
attr_accessible :amount, :expense_date, :project_id, :expense_type_id, :user_id
belongs_to :project
belongs_to :user
belongs_to :expense_type
has_one :expense_approval
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_many :expenses, foreign_key: :user_id
end
You have a mildly complex set of relationships. Now you have to think of the query semantics you’ll require in your app.
Remembering your original post subject ‘Nesting… needed?’
That depends on the various query semantics you’d like in your app.
The most obvious ‘nested’ relationship is:
So if in your app, it only ever makes sense to query expenses that belong to a project, you might consider creating nested routes i.e.:
config/routes.rb:
Assume that is the ONLY route in your app. The only way to reference any expense is to do it through the project it belongs to. So this query would be available:
BUT, look at the NUMEROUS routes generating with the above entry in routes.rb. To see, run ‘rake routes’ with the above nested routes included in ‘routes.rb’ , then remove the above entry from ‘routes.rb’ and run ‘rake routes’ again.
The nested routes adds ALOT of routes. It may add MANY routes you don’t need. If that is the case, you may want to take a different approach. DON’T use the nested routes, but instead HAND CRAFT only the routes you really need.