Reddirt
Reddirt

Reputation: 5953

Rails create associated records in a controller

I have 3 tables:

project

has_many :answers

questions --> questions every project must answer

 has_many :answers

answers

belongs_to :project

belongs_to :question

So, when I create a new project, I would like to loop through the questions and create an answer record. Then the user can see all of the questions and enter their answers.

In the project controller, I'm trying to create those records. But, the following isn't working:

  before_create :create_answers

protected
def create_answers
  Questions.each do |i|
    self.answers.build  contact_id: self.contact_id, question_id: Question[i].id
  end
end

Thanks!!!

Upvotes: 0

Views: 935

Answers (1)

Josh Rieken
Josh Rieken

Reputation: 2266

Instead of:

Questions.each

Do:

Question.all.each

All that code will need to go in the Project model, not the ProjectsController.

And instead of:

Question[i].id

Do:

i.id

Make sure those attributes are attr_accessible as well.

All together:

before_create :build_answers

protected
def build_answers
  Question.all.each do |question|
    answers.build contact_id: contact_id, question_id: question.id
  end
end

And the attr_accessible bit:

attr_accessible :contact_id, :question_id

Upvotes: 2

Related Questions