Two Model Classes - One Database Table
Do you ever do this?
I'm writing a Rails app. I have a situation where I have a Task model (and table), the Task has attributes, people that are allowed to view it, and a hierarchy (it may be under a project, or a business).
I also have an AssignmentController that exposes some views and functionality to the individual t开发者_开发技巧hat's assigned to the Task - The AssignmentController uses Task.find to get the task and is the same object as the Task - it's just being updated by the Assignee and only a few columns are available to the assignee. In this case, I wanted to hide some UI, change the layout to fit the business, and the hierarchy didn't matter for the assignee of the task.
What I'm thinking of doing is creating a Task model and an Assignment model that both point at the same table (the task table). I don't see why I shouldn't do this. It would allow me to thin down the Assignment model class and isolate methods that are only used by the Task. it would also make much of the code cleaner, as far as I can tell.
I don't see much about this pattern when I search on the web. Any opinions about this?
Appreciate your thoughts...
If I understood correctly you want to subclass tables :) Nice idea, don't see why it wouldn't work... set_table_name "tasks" will do it, or just subclass the Task model. But in both cases you'll get into trouble with the associations, you'll have to define belongs_to :task and belongs_to :assignment for any has_many association there it you want to do it right...
Edit: Actually forget what I said :) http://railscasts.com/episodes/154-polymorphic-association
You should have a join table between Assignee and Tasks. Your proposal would cause your views to be littered with if statements on weather or not you have an assignee or task. If you find that you are using similar chunks of html between the two, you can simply use partials.
Also, your proposal somewhat defies database normalization. Normalization isn't just what you need today, but what you might need tomorrow. If you have no more information on an assignee than a username it might be okay to have the same table for both models (kind of). But what about later when you want to have more information on Assignees?
精彩评论