1

I have answers associated with questions, but after creating a new question, it should have 0 answers.

In this chunk of code

<% @question.answers.each do |ans| %>

    <div class="container">
        <div class="row-fluid">
        </p>

        <p>
            <%= ans.answer %>
        </p>

        <h5><em>
            <%= ans.commenter %> posted 
            <%= link_to "Answer comments", [@question,ans] %>

        </em></h5>

    </div>
</div>
<% end %>

Even after newly creating a question, a non-existent answer without an answer field appears on the view, and there's a link to question/1/answers (obviously answers isn't a valid path). Is there a reason for this?

user3340037
  • 731
  • 2
  • 8
  • 23

2 Answers2

2

You create some answers instances after creating the question I suppose. It may be the question_controller code or models/question.rb code. You can analyze the code and find the issue over there.

The simple workaround is to add condition

<% if @question.answers.empty? %>
  <p>No answers yet.</p>
<% else %>
  <% @question.answers.each do |ans| %>
  ...
<% end %>
alex
  • 3,682
  • 3
  • 21
  • 22
1

.build

This problem will likely be caused by the saving of an answer each time you create a question

I'd imagine you're doing something like this:

#app/controllers/questions_controller.rb
def new
    @question = Question.new
    @question.answers.build
end

def create
    @question = Question.new(question_params)
    @question.save
end 

private

def question_params
    params.require(:question).permit(answers_attributes: [])
end

Each time you build an associative object, you're basically creating an entry in the database, which will be associated to the parent object

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147