在 Rails habtm 连接中添加额外字段
Add extra field in Rails habtm joins
我在用户、团队之间有这种关系
class CreateTeamsUsers < ActiveRecord::Migration
def change
create_table :teams_users, :id => false do |t|
t.references :user
t.references :team
t.timestamps
end
end
end
class User < ActiveRecord::Base
has_and_belongs_to_many :teams
end
class Team < ActiveRecord::Base
has_and_belongs_to_many :users
end
问题是我想在 HABTM 中添加额外的属性,属性名称是 "user_name"
如何做到这一点?
简短版本,如果不进行一点重构,您将无法完成您想要做的事情。这是我的做法(如果有语法问题,我深表歉意,我是凭记忆做的,我没有测试过代码,但原理是正确的)
创建一个新模型来表示团队的 "membership"(可能称之为 "Membership")和关联迁移以创建 table:
class Membership
belongs_to :team
belongs_to :user
end
然后更改您的团队和用户模型以使用此新模型:
class User
has_many :memberships
has_many :teams, through: :memberships
end
class Team
has_many :memberships
has_many :users, through: :memberships
end
重构到此为止后,向 "memberships" 添加额外的列/属性就很容易了,因为您可以像对待任何其他模型一样对待它。
您可以使用 has_many
和 has_many :through
.
而不是 HABTM
class User < ActiveRecord::Base
has_many :memberships
has_many :team, through: :membership
end
class Membership < ActiveRecord::Base # This would be your old 'join table', now a full model
belongs_to :user
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
end
我在用户、团队之间有这种关系
class CreateTeamsUsers < ActiveRecord::Migration
def change
create_table :teams_users, :id => false do |t|
t.references :user
t.references :team
t.timestamps
end
end
end
class User < ActiveRecord::Base
has_and_belongs_to_many :teams
end
class Team < ActiveRecord::Base
has_and_belongs_to_many :users
end
问题是我想在 HABTM 中添加额外的属性,属性名称是 "user_name" 如何做到这一点?
简短版本,如果不进行一点重构,您将无法完成您想要做的事情。这是我的做法(如果有语法问题,我深表歉意,我是凭记忆做的,我没有测试过代码,但原理是正确的)
创建一个新模型来表示团队的 "membership"(可能称之为 "Membership")和关联迁移以创建 table:
class Membership
belongs_to :team
belongs_to :user
end
然后更改您的团队和用户模型以使用此新模型:
class User
has_many :memberships
has_many :teams, through: :memberships
end
class Team
has_many :memberships
has_many :users, through: :memberships
end
重构到此为止后,向 "memberships" 添加额外的列/属性就很容易了,因为您可以像对待任何其他模型一样对待它。
您可以使用 has_many
和 has_many :through
.
class User < ActiveRecord::Base
has_many :memberships
has_many :team, through: :membership
end
class Membership < ActiveRecord::Base # This would be your old 'join table', now a full model
belongs_to :user
belongs_to :team
end
class Team < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
end