Form results don't display on page

I am trying to do this tutorial on Youtube but I can't get the last part to work where what you have submitted in the form is supposed to display in an area below it.

The data is getting into the Sqlite database as it should.

app/controllers/students_controller.rb:

class StudentsController < ApplicationController
  def new
    @student = Student.new
  end

  def create
    @student = Student.new(student_params)
    if @student.save
      redirect_to new_student_path
    end
  end

 private
 def student_params
    params.require(:student).permit(:firstname, :lastname)
 end  
end

app/views/students/new.html.erb:

<%= form_for @student do |f| %>
  First <%= f.text_field :firstname %><br>
  Last <%= f.text_field :lastname %><br>
  <%= f.submit %>
<% end %>

<p>Display student info:</p> 

# This is what doesn't work
<% if !@students.blank? %>
  <% for item in @students %>
    <%= item.firstname %>
  <% end %>
<% else %>
<% end %>

The video uses Rails 3 and I am using Rails 5.

Any ideas? Thanks in advance!

1 answer

  • answered 2017-06-17 17:53 Sebastián Palma

    You're defining a @student variable as Student.new(student_params) in your create method, but then in your view you're trying to get a @students variable, so that's one problem.

    Also you expect to receive such variable in the view, but you're not sending it again, so what you could do is to use render to get the new view again, but with location you can pass the saved record.

    Something like:

    # students_controller.rb
    def new
      @student = Student.new
    end
    
    def create
      @student = Student.new(student_params)
      # check if @student is saved and render new passing it
      if @student.save
        render :new, location: @post
      end 
    end
    

    And this way in your view you can check if @student isn't nil and working with it:

    # new.html.erb
    <% if @student %>
      <!-- do any thing -->
    <% end %>