ruby-on-rails - 在 Rails 中重构相同的模型

标签 ruby-on-rails ruby dry

我使用连接表解决方案来创建友谊,如下所示:

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/

相关文章:

ruby-on-rails - 104 : Connection reset by peer: nginx + rainbows + over 1 mb uploads

ruby-on-rails - rails 3 : Permalink public profile

ruby-on-rails - 用于多个帐户的带有 IMAP IDLE 的 Ruby on Rails

ruby - 新 rvm/ruby/pg/rails 设置的最佳安装流程

java-8 - Consumer 封装 try catch 逻辑不起作用

ruby-on-rails - rails : Functionals Test fails for undefined method in view

ruby-on-rails - 在 Rails 中调用私有(private)方法?

ruby - rspec 和 heckle 的兼容性如何?

perl - Catalyst:如何声明一个全局子程序

ruby - 简化 Ruby 方法 : leave unnecessary variables off