2017-11-03 11 views
0

モデルはpost_consultantconsultantです。 post_consultantconsultantの両方がEmployeeモデルへの参照です。だからあなたが言うことができる:私はそれを書くことが出来るのですかレールアソシエーション:同じモデルの2つの発生

モデル

Class Consultation < ActiveRecord::Base 
    has_one :employee # for consultant 
    has_one :employee # for post_consultant 
end 

移行

create_table "consultations", force: :cascade do |t| 
    t.boolean "showed_up" 
    t.boolean "signed_up" 
    t.integer "client_id" 
    t.integer "consultant_id" 
    t.integer "post_consultant_id" 
end 


正しいモデル:

class Consultation < ActiveRecord::Base 
    belongs_to :consultant, class_name: "Employee", foreign_key: "consultant_id" 
    belongs_to :post_consultant, class_name: "Employee", foreign_key: "post_consultant_id" 
end 
+0

post_consultantとコンサルタントはモデルですか? – krishnar

+0

post_consultantとコンサルタントのための外部キー? – krishnar

+0

従業員だけが –

答えて

3
Class Consultation < ActiveRecord::Base 
    belongs_to :consultant, :class_name => "Employee", :foreign_key=> "consultant_id", dependent: :destroy 
    belongs_to :post_consultant, :class_name=>"Employee", :foreign_key=> "post_consultant_id", dependent: :destroy 
end 
+0

というモデルです。私は試してみるとちょっと変わっています: 'c = Consultation.new'。 'e = Employee.first'。 'ActiveModel :: MissingAttributeError:未知の属性 'consultant_id''を書き込めません。 –

+0

あなたは、consultant_idとpost_consultant_idというフィールドがテーブル相談の中にあるかどうか確認してください。スキン –

+0

私は相談テーブル –

0

あなたは同じモデルを参照する複数の関係を定義することができます。

Class Consultation < ActiveRecord::Base 
    has_one :consultant, class_name: 'Employee', foreign_key: :consultant_id 
    has_one :post_consultant, class_name: 'Employee', foreign_key: :post_consultant_id 
end 

ノート:あなたは上記の構文を使用して、各団体のためのu使用している言及方の外部キー。

+0

上記のコメントにコメントしてください –

関連する問題