Reputation: 9627
I have this two models:
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
But when I write in rails console following:
q=Question.new
q.save
a=Answer.new
a.question = q
a.save
q.answers.size
It gives me zero.
irb(main):026:0> q.answers.size
=> 0
But when I write this:
Answer.where(:question_id => q.id).size
it gives me 1
SO WHAT DO I DO?
In case you need it - answers and question migrations:
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
Upvotes: 0
Views: 41
Reputation: 2775
You need to use inverse_of option in your relationship.
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
So when you do:
a.question = q
Rails will do this for you(in memory):
q.answers << a
And you don't need to reload the q again.
Upvotes: 2