2016-05-23 18 views
0

私は3つのモデルを持っています。 現在、Rails:3つのモデル間のポリモーフィックな関連付けを追加する

class User < ActiveRecord::Base 
    has_one :agency 
    has_one :client 
end 

class Client < ActiveRecord::Base 
    belongs_to :users 
end 

class Agency < ActiveRecord::Base 
    belongs_to :users 
end 

私はこのような関連付けを変更し、ポリモーフィックな関連を作成するには:

User belongs_to :role , :polymorphic => true 

Client has_one :user, as: :role 
Agency has_one :user, as: :role 

私は初心者レールの開発者です。どうすればこれを達成できますか?移住を書こうとしていますか?

答えて

1

ユーザモデルにrole_idrole_typeの2つのフィールドを追加する必要があります。あなたは

class User < ActiveRecord::Base 
    belongs_to :role, polymorphic: true   
end 

class Client < ActiveRecord::Base 
    has_one :user, as: :role, class_name: 'User' 
end 

class Agency < ActiveRecord::Base 
    has_one :user, as: :role, class_name: 'User' 
end 

今すぐレールサーバーを再起動し、次のように関連付けを変更する必要が rake db:migrateを実行した後

rails g migration addNewFieldsToUsers role_id:integer role_type:string 

を次のように新しい移行を作成することができます。

0

移行は不要です。データベース内のモデル間の関連付けはありません(これは移行が変わるものです)。

app/models/user.rbapp/models/location.rbを変更する必要があります。単にユーザーからbelongs_to:を削除してloa:belongs_to: userに追加してください。

+0

実際に私は私の質問を編集しました。あなたはこれに答えることができますか?早急に適切な質問をしないと申し訳ありません。 – Abhishek

関連する問題