I'll try to explain this as best as I can... I have an Assignment and User model, with users having many assignments and the assignment belonging to a user. But, along with assignments having one owner, I'd like for assignments to have multiple "secondary" owners, through the use of "has_many :through => assignments_users". Is this possible? I tried to implement this but I got an error saying an assignment with the user id of 1 can't be found, when there were assignments with the user_id as 1, but it was looking through the assignments_users table. Thanks!
Andrew wrote:
I'll try to explain this as best as I can... I have an Assignment and User model, with users having many assignments and the assignment belonging to a user. But, along with assignments having one owner, I'd like for assignments to have multiple "secondary" owners, through the use of "has_many :through => assignments_users". Is this possible? I tried to implement this but I got an error saying an assignment with the user id of 1 can't be found, when there were assignments with the user_id as 1, but it was looking through the assignments_users table. Thanks!
User has_many :assignments_users has_many :assignments, :through => :assignments_users end
Assignment has_many :assignments_users has_many :users, :through => :assignments_users belong_to :owner, :class => User, :foreign_key => :owner_id end
AssignmentUser belongs_to :assignment belongs_to :user end
Would provide these message: @user.assignments @assignment.users @assignment.owner
However, I would likely alter the naming of these objects somewhat.
Something like:
User has_many :assignments has_many :projects, :through => :assignments end
Project has_many :assignments has_many :users, :through => :assignments belong_to :owner, :class => User, :foreign_key => :owner_id end
Assignment belongs_to :project belongs_to :user end
In this case User and Project are solidly nouns. Assignment (although could be a noun) servers better for linking Users to Projects. However, this is really just semantics, although I do make an effort to give my joining models a good solid name when using has_many :through.
I like this because the act of assigning a project to a user can be more easily thought of from a RESTful perspective. In order to "create" an association between a user and a project, one would create an assignment.
assignments_controller