0

フィールド名と性別を持つユーザーモデルがあります。また、ユーザーは他のユーザーと「配偶者」と呼ばれる 1 対 1 の関連付けを行うことができます。関連付けは、男性ユーザーと女性ユーザーの間で行う必要があります。

railscasts self-referential-associationの助けを借りて、このような基本的な関連付けを作成します。

class User < ActiveRecord::Base
  has_one :spouse_list
  has_one :spouse, :through => :spouse_list

  has_one :inverse_spouse_list, :class_name => "SpouseList", :foreign_key => "spouse_id"
  has_one :inverse_spouse, :through => :inverse_spouse_list, :source => :user
end

class SpouseList < ActiveRecord::Base  
  belongs_to :spouse, :class_name => "User"  
  belongs_to :user  
end

SpouseList には、:spouse_id、:user_id、

上記の関連付けでは、1 人のユーザーに対して多くの行を作成でき、@user.spouse_list.spouse.name で配偶者にアクセスすると最初の行が表示されます

男性ユーザーと女性ユーザーを制限するにはどうすればよいですか?

4

1 に答える 1

1

最後に、以下の条件に対して 1 対 1 の自己関連付けを行いました。

「ユーザーは、他のユーザーと「配偶者」と呼ばれる 1 対 1 の関連付けを行うことができます。関連付けは、男性ユーザーと女性ユーザーの間で行う必要があります」

フィールドspouse_idをユーザーモデルに追加し、カスタム検証で自己関連付けを作成し、

class User < ActiveRecord::Base

  belongs_to :spouse, :class_name => 'User', :inverse_of => :base_user, :foreign_key => "spouse_id"
  has_one :base_user, :class_name => 'User', :inverse_of => :spouse

  validate :validate_spouse_gender

  private
  def validate_spouse_gender
    errors.add(:spouse_id, 'could not be with same sex') if spouse && spouse.sex == sex
  end

end

これで、男性ユーザー A は、B の性別が女性である場合にのみ、別のユーザー B と配偶者として関連付けることができます。

それが誰かを助けることを願っています。

于 2012-11-26T08:05:40.407 に答える