ruby on rails - Undefined method when rendering form partial -


on questions index page have list of questions. want able answer each question right on page rendering answers form. getting error when try , that:

undefined method `answers' #<question:0x00000103dc0100> 

it highlights second line of answers controller:

def create @question = question.find(params[:question_id]) @answer = @question.answers.new(answer_params) @answer.save     end 

here view:

 <% @questions.each |question| %>  <%= question.body %>  <%= render :partial => "answers/form", locals: {question:question} %>  <% end %> 

and form looks this:

 <%= simple_form_for [question, answer.new] |f| %>  <%= f.input :body %>  <% end %> 

lastly, questions controller:

 def index   @questions = @comment.questions.order       @answer = answer.new   end  

since have belongs_to has_one relationship, correct association this:

question.find(params[:question_id]).answer 

note answer singular. because each question has one answer - thus, instances of question not have method answers, indicated in exception.

if wanted each question have multiple answers, you'd define following associations:

# app/models/question.rb class question < activerecord::base   has_many :answers end  # app/models/answer.rb class answer < activerecord::base   belongs_to :question end 

with belongs_to has_many relationship, you'd able access multiple answers on each question follows:

question.find(params[:question_id]).answers 

update 1:

there couple ways add answer question.

option 1: utilizing rails build method made available has_one association:

question.find(params[:question_id]).build_answer(answer_params) 

option 2: directly assign answer question:

answer = answer.first question = question.first  question.answer = answer 

in either method, note that, because each question limited a single answer, question's existing answer replaced, rather added to.

update 2:

here's how controller action should in entirety utilizing each of suggested methods:

option 1:

# app/controllers/answers_controller.rb def create   @question = question.find(params[:question_id])   @question.build_answer(answer_params) end 

option 2:

# app/controllers/answers_controller.rb def create   @answer = answer.new(answer_params)   @question = question.find(params[:question_id])   @question.answer = @answer end 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -