Rails nested_attributes Could not find the association :question_category in model Question

 間違えたコード:


/ <% @categories.each do |c| %>
/ <%= check_box :category, :id, {}, c.id %>
/ <%= c.name %>
/ <% end %>

/ - @categoriesid.each do |id|
/ = check_box :id, id
/ category, nil
/ = category.name

/ - @categories.each do |category|
/ = check_box :category_id, { multiple: true }, category, nil
/ = category.name


/ - @categories.each_with_index do |category, i|
/ = check_box_tag 'category[:id]', "#{i+1}"
/ = category.name

/ - @categories.each_with_index do |category,i|
/ = check_box_tag "category#{i+1}", category.id

コントローラーのコード:

 def create
    @question = Question.new(question_params)
    @categories = @question.categories.new(category_params)
    # @category = Category.new[]
    categories_attributes
    if @question.save
      redirect_to user_question_path(@user, @question)
    else

 

エラー:

ActiveRecord::HasManyThroughAssociationNotFoundError at /users/14/questions
Couldnot find the association :question_category in model Question
(1)
引用:activerecord - Could not find the association problem in Rails - Stack Overflow

In the ApplicationForm class, you need to specify ApplicationForms's relationship to 'form_questions'. It doesn't know about it yet. Anywhere you use the :through, you need to tell it where to find that record first. Same problem with your other classes.

So

# application_form.rb
class ApplicationForm < ActiveRecord::Base
  has_many :form_questions
  has_many :questions, :through => :form_questions
end

# question.rb
class Question < ActiveRecord::Base
  belongs_to :section
  has_many :form_questions
  has_many :application_forms, :through => :form_questions
end

# form_question.rb
class FormQuestion < ActiveRecord::Base
  belongs_to :question
  belongs_to :application_form
  belongs_to :question_type
  has_many :form_questions_answers
  has_many :answers, :through => :form_question_answers
end

That is assuming that's how you have it set up.

shareimprove this answer
 
 



1  
i've done this a thousand times and even when staring at my other working hmt models, couldn't see I was missing the other has_many...lol... –  Danny May 29 '13 at 15:59
(2)