Rails Migrations - Alternative name for a foreign key?
In my application I have 3 tables, users, lists, tasks.
Users and lists is a many-to-many relationship, tasks belong to lists, and users can complete tasks.
For my migration, when a user completes a list I'd like to store who it was completed by in the database but I'开发者_如何学编程m unsure how to do this.
I could simply add t.integer :user_id
to my tasks migration, though I'd like to refer to it as .completed_by
. Something that references the :user_id in my User table but is named :completed_by?
As MrDanA mentioned, you can specify a different foreign_key, but I would recommend against it. If you can, your db structure will be more understandable at the low level if you stay with entity name conventions.
In the future, it'll be immediately obvious that user_id points at the user table, while a new programmer won't be able to tell that completed_by points at the user table without exploring code. If you do want to have a specific name, or need more than one user association, something like "completed_user_id" remains clear at both the app and db levels.
You can then add methods like:
has_one :user
has_one :completed_by, :class_name => "User", :foreign_key => "completed_user_id"
or
has_one :user
def completed_by
self.user.id
end
etc.
In your migration, add t.integer :completed_by
Then, in your model, instead of:
has_one :user
do:
has_one :user, :class_name => "User", :foreign_key => "completed_by"
or even customize the association name, like:
has_one :completer, :class_name => "User", :foreign_key => "completed_by"
精彩评论