3

私は女性がいることができる広告を持っていますが、タイプが「クラブ」である場合に限ります。

それを行うためのレールウェイはありますか?特に女性のオブジェクトを作成しない場合はどうなりますか?親がtype=clubの場合、作成する前に女性オブジェクトを確認する必要がありますか?

class Advertisement < ActiveRecord::Base

  validates_inclusion_of :type, in: %w(club lady)

  has_many :ladies, :dependent=>:destroy

  #only have ladies if the club =
  def ladies 
    return nil unless type == "club"
    super    
  end

end

Rails3.2を使用しています。

4

3 に答える 3

3

それを行うためのRailsの方法はSTIです。

 class Advertisement < ActiveRecord::Base
 end

 class LadyAd < Advertisement
   has_many :ladies, :dependent=>:destroy
 end

そして、LadyAdオブジェクトだけが女性を持つことができます。

于 2013-01-05T20:36:58.107 に答える
0

おそらくアクティブレコードアソシエーション拡張機能を使用しています:(proxy_association.ownerを使用)

http://guides.rubyonrails.org/association_basics.html#association-extensions

module LadiesAtClub
  def at_club
    # you may need to iterate over an array or something here...
    proxy_association.owner.type == 'club'
  end
end

class Advertisement < ActiveRecord::Base
  has_many :ladies :extend => LadiesAtClub
end
于 2013-01-11T01:18:57.043 に答える
0

これはすべて、構成(has_many)と継承(lady <advertising)を混合しているようですが、これは(技術的および概念的に)あまり意味がありません。これが当てはまり、LadyオブジェクトとClubオブジェクトを使用していない場合は、少なくともタイプの名前をad_typeに変更する必要があります...

自己参照結合を作成していると仮定すると、club_id列が必要になります。

class Advertisement < ActiveRecord::Base
   has_many :ladies, -> {where(type: 'club')}, class_name: "Advertisment"
 end
于 2013-01-11T12:13:39.473 に答える