私は現在、4.0.0beta1の下で開発中のプロジェクトで、各ユーザーをエンティティにリンクできるユーザーベースの認証が必要でした。私はちょっとレールに新しく、いくつかのトラブルを抱えていました。has_one throughと複数表の継承によるポリモーフィックな関連
モデルは以下の通りです:
何私が必要とするには、ユーザが(私はエンティティを呼び出すことになりますどのようなものを二つがある代理店またはクライアントのどちらか一方にリンクできるようにするためであるclass User < ActiveRecord::Base
end
class Agency < ActiveRecord::Base
end
class Client < ActiveRecord::Base
belongs_to :agency
end
)。それはリンクを全く持たず、最大でも1つのリンクを持つことができます。
私が探した最初のものは、レールにMutli-Table inheritance(MTI)を行う方法でした。しかし、いくつかのものは私をブロックされた:
- それはMTIは、ソリューションを実装する
- 宝石が古いとすぎるかCOMPLEXE見えたな私と初心者のための実装がちょっとハードに見えたか、箱から出して
- 利用できませんでした彼らはしばらく
用に更新されていなかったとして完成
私は昨日から、この上にあるとさえRails polymorphic has_many :throughとActiveRecord, has_many :through, and Polymorphic Associations
の助けを借りてそれを動作させるためにいくつかの時間がかかった私は仕事上の問題から、例を作ることができたが、それはしばらくして私を取りました最後に2つの問題があります:
- ユーザーの関係をhas_one関連に変換し、リンクされたエンティティに「盲目的に」アクセスする方法はありますか?
- ユーザーが複数のエンティティを持つことができないように制約を設定するにはどうすればよいですか?
- 私がしたいことをする良い方法はありますか?
移行ファイル:
class CreateUserEntities < ActiveRecord::Migration def change create_table :user_entities do |t| t.integer :user_id t.references :entity, polymorphic: true t.timestamps end add_index :user_entities, [:user_id, :entity_id, :entity_type] end end
モデル:
class User < ActiveRecord::Base has_one :user_entity has_one :client, through: :user_entity, source: :entity, source_type: 'Client' has_one :agency, through: :user_entity, source: :entity, source_type: 'Agency' def entity self.user_entity.try(:entity) end def entity=(newEntity) self.build_user_entity(entity: newEntity) end end class UserEntity < ActiveRecord::Base belongs_to :user belongs_to :entity, polymorphic: true validates_uniqueness_of :user end class Client < ActiveRecord::Base has_many :user_entities, as: :entity has_many :users, through: :user_entities end class Agency < ActiveRecord::Base has_many :user_entities, as: :entity has_many :users, through: :user_entities end
はあなたが私はゲッターと私セッターを追加見ることができるようにここで完全に動作する例を示します
@Crystark上記のファイルをテストすると、次のエラーが発生します。NameError:初期化されていない定数UserWithClient –