Ruby on rails 你有很多或属于你的作品吗

Ruby on rails 你有很多或属于你的作品吗,ruby-on-rails,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 它给我零分 irb(main)

我有两种型号:

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
它给我零分

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
classcreateanswers
你需要在你的关系中使用相反的选项

 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
Rails将为您执行此操作(在内存中):


q.answers你需要在你的关系中使用选项的倒数

 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
Rails将为您执行此操作(在内存中):


q.answers尝试重新加载问题
q.reload
@Deepak帮助很大,谢谢!尝试重新加载问题
q.reload
@Deepak它很有帮助,谢谢!
 a.question = q
q.answers << a