簡體   English   中英

Rails多態has_many / belongs_to

[英]Rails polymorphic has_many/belongs_to

我有以下型號:

User
- type

Account
- user_id

Aide
- user_id

Provider
- user_id

用戶可以具有類型['account','aide','provider'],並且可以具有一個類型中的許多類型,但不應具有與之關聯的多種類型。 因此,“助手”類型的用戶有很多助手,但不應有任何帳戶或提供者。

在Rails中是否存在處理此類關聯的既定方法? 在傳統的定義中,它並不是真正的多態性,更多的是父代的類型定義了子代的類型。

  • 帳戶屬於用戶
  • 助手屬於用戶
  • 提供者屬於用戶
  • 用戶有多個帳戶
  • 用戶有很多助手
  • 用戶有很多提供商

然后可以在User模型類中添加一個驗證方法,如下所示:

class User < ActiveRecord::Base # your User model
  validate :pick_a_name

  private

  def pick_a_name
    # check presence of associations that aren't of the users's type

    associations = %w{accounts aides providers} # use a constant

    associations.each do |a|
      if (a != self.type.pluralize) && send(a).present?
        # if such associations are present, add errors here
      end
    end
  end
end

在其他類別中:

class Account # your account model
  validate :pick_a_name

  private

  def pick_a_name
    if (user.type != 'account')
      # add errors here
    end
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM