has_many或belongs_to工作错误

时间:2016-09-21 10:16:01

标签: ruby-on-rails

我有两个模型:

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
  has_many :edits, dependent: :destroy
end

class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers, dependent: :destroy
end

但是当我在rails控制台中写下:

q=Question.new
q.save

a=Answer.new
a.question = q
a.save

q.answers.size 

它给我零。

irb(main):026:0> q.answers.size
    => 0

但是当我写这篇文章时:

Answer.where(:question_id => q.id).size

它给了我1个

我该怎么做?

如果您需要它 - 答案和问题迁移:

class CreateAnswers < ActiveRecord::Migration
  def change
    #execute "DROP TABLE #{:answers} CASCADE" 

    create_table :answers do |t|
      t.text :body
      t.references :user, index: true, foreign_key: true
      t.references :question, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

class CreateQuestions < ActiveRecord::Migration
  def change
    #execute "DROP TABLE #{:questions} CASCADE" 
    create_table :questions do |t|
      t.string :title
      t.text :body
      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

1 个答案:

答案 0 :(得分:2)

您需要在关系中使用inverse_of选项。

 class Answer < ActiveRecord::Base
   belongs_to :user
   belongs_to :question, inverse_of: answers
   has_many :edits, dependent: :destroy
 end

 class Question < ActiveRecord::Base
   belongs_to :user
   has_many :answers, inverse_of: question, dependent: :destroy
 end

所以当你这样做时:

 a.question = q

Rails将为您(在内存中)执行此操作:

q.answers << a

而且你不需要重新加载q。