Answer has_one:オプションとOption has_many:answersになるように私のモデルを設定しようとしています。それらは、AnsweredOptionsテーブルを介して結合されます。ここでは三つのモデルがあります:回答has_one:オプションとオプションhas_many:answersになるようにモデルの関連付けを設定するには?
class Answer < ActiveRecord::Base
has_many :answered_options
has_one :option, through: :answered_options, source: :options
belongs_to :question
end
class Option < ActiveRecord::Base
belongs_to :question
has_many :answered_options
has_many :answers, through: :answered_options, source: :answers
end
class AnsweredOption < ActiveRecord::Base
belongs_to :answer
belongs_to :option
end
私は、最初のソースなしの両方上記のモデルを試してみましたが、私は分後に下記共有する同じエラーを取得しています。 answered_optionsため
スキーマ:ここ
create_table "answered_options", force: :cascade do |t|
t.integer "answer_id"
t.integer "option_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
私はコンソールでAnswer.first.optionを実行したときに私が取得エラーです:ここでは
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :options in model AnsweredOption. Try 'has_many :option, :through => :answered_options, :source => <name>'
は、私はオプションを実行したとき、私は取得エラーです。最初の回答者:
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :answers in model AnsweredOption. Try 'has_many :answers, :through => :answered_options, :source => <name>
これらのエラーが発生した後、自分の関連付けにsource:オプションを追加しましたしかし、それは何も変わらなかった。私はここで間違って何をしていますか?助けてくれてありがとう。
だからもちろん、外部キーとして機能するためには、answersテーブルに 'option_id'が必要です。 – jaydel
私は、has_oneオプションの代わりにbelongs_to:オプションを使用しなければならないことを除いて、あなたが提案した方法に変更しました。これは適切な方法ですか、私はhas_oneの関連付けに間違っていますか? – srlrs20020
'belongs_to'と' has_one'にはいくつかの違いがあります。しかし機能的には、それらは非常に似ています。 'belongs_to'がうまくいくならば、それを使ってください。あなたが2つの違いについてもっと知りたいのであれば、ここに[リンク](http://requiremind.com/differences-between-has-one-and-belongs-to-in-ruby-on-rails/)があります。 – davidhu2000