我使用连接表解决方案来创建友谊,如下所示:
class Contact < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User", :foreign_key => :friend_id
def self.request(user, friend)
unless user == friend
current = find_by_user_id_and_friend_id(user, friend)
unless current
transaction do
create :user => user, :friend => friend, :status => "pending"
create :user => friend, :friend => user, :status => "requested"
end
end
end
end
...
我去创建组成员资格,发现了相同的情况:
class Member < ActiveRecord::Base
belongs_to :user
belongs_to :network
def self.request(user, network)
current = find_by_user_id_and_network_id(user, network)
unless current
transaction do
create :user => user, :network => network, :status => "pending"
create :user => network, :network => user, :status => "requested"
end
end
end
...
我用阻塞使这个变得复杂,并且有很多重复的代码。
由于belongs_to :friend, :class_name => "User", :foreign_key => :friend_id
,将该 key 识别为专门代表用户,我认为我无法逃脱对用户 <-> 用户和用户 <-> 网络使用 Contact
。我可以通过 network_id
让它也belongs_to
一个网络,但我仍然觉得我必须加倍方法来解决这个问题。我想我可以将 type
(:friend
或 :network
)传递给每个方法并使用它,例如:
create :user => user, type => target, :status => "pending"
create :user => target, type => user, :status => "requested"
但是,有更好的解决方案吗?
我的另一个想法是始终使用术语 :friend
,但也许使用混合类或抽象类,并在之间以不同的方式定义 belongs_to :friend
行这两个文件。
最佳答案
关于ruby-on-rails - 在 Rails 中重构相同的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573160/