controller - Rails: Why isn't the 'create' action saving the newly created Quiz instance? -
my form gets passed 'new' quiz (not saved database). form partial looks this:
<%= form_for(@quiz) |f| %> <p> <%= f.check_box(:answer1) %> <%= f.check_box(:answer2) %> <%= f.check_box(:answer3) %> <%= f.check_box(:answer4) %> <%= f.check_box(:answer5) %> <%= f.check_box(:answer6) %> <%= f.check_box(:answer7) %> <%= f.check_box(:answer8) %> </p> <p> <%= f.submit("get results!") %> </p> <% end %>
here quizzescontroller#create action:
def create @results = quiz.create(post_params) #from private method if @results.save redirect_to results_path else #error handle here end end
...which gets triggered when user clicks 'get results' on quiz form. , post_params method looks this:
def post_params params.require(:quiz).permit(:id, :user_id, :answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8) #add other attributes here end
my results/index.html.erb looks this:
<div class="container"> <!-- example row of columns --> <div class="row"> <h1>results</h1> <p><%= @results.inspect %></p> </div> </div>
but 'inspected' quiz instance returns 'nil' answers1, answers2 etc attributes. idea why be? there i'm not doing save user's answers database?
the reason shows nil because not setting variable.
after creating , saving, redirect results_path
, variable @results
not persist during redirect. without seeing full code, i'll have guess @ naming conventions there 2 ways this.
1) if want redirect index in code index action, can set variable:
@results = quiz.last
this easy work in development because user , return last quiz created. not great in production.
2) alternative redirect show action quiz.
def create @results = quiz.new(post_params) if @results.save redirect_to result_path(@results) else # error handle here end end
again, have had guess result_path
correct path. without seeing full routes file, cannot sure can rename accordingly if necessary.
Comments
Post a Comment