【发布时间】:2016-03-16 11:16:23
【问题描述】:
我希望在寻求这种关联之前确保我的方法是正确的。实现听起来太复杂了,所以我认为我的计划一定有问题。我正在使用符合 Rails 存储约定的结构化 (SQL) 数据存储。我拥有的是一个用户模型,它有一个电子邮件地址password_digest,并在架构中具有名称。
class User < ActiveRecord::Base
has_many :posts
end
我想实现一个has_many 关联到朋友集合,以便用户可以belong_to 用户(作为朋友)。我希望能够让User.last.friends.last 在正确构建和填充时返回一个用户对象。
我相信我可以为这种关联创建一个模型,例如:
Class Friend < ActiveRecord::Base
belongs_to :user
belongs_to :friendlies, class: 'User'
end
Class User < ActiveRecord::Base
has_many :posts
has_many :friends
has_many :friendly, class: 'Friend'
end
但我认为这将需要我添加模型并使用User.last.friends.last.user 进行查询所以我在想这是has_and_belongs_to_many 关系。我可以摆脱以下(或类似的):
class User < ActiveRecord::Base
has_and_belongs_to_many :friends, class: 'User'
end
我找到this:
class User < ActiveRecord::Base
has_many :user_friendships
has_many :friends, through: :user_friendships
class UserFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id'
还有this(自称“标准”):
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships, :dependent => :destroy
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id", :dependent => :destroy
has_many :inverse_friends, :through => :inverse_friendships, :source => :user, :dependent => :destroy
我认为这需要Friendship 模型。我不觉得我需要一个友谊模型。我认为class UserFriendship 方法看起来不错,但它需要一个额外的模型。现在进入问题:
我能否在不产生额外模型的情况下与将用户与作为用户的朋友相关联的表建立
has_and_belongs_to_many关系?“以防万一”以后出现其他要求,是否谨慎使用附加模型?
【问题讨论】:
标签: ruby-on-rails data-modeling