Zack Shapiro
Zack Shapiro

Reputation: 6998

Struggling to view all database entries in my HTML output

I've got a pretty simple Ruby on Rails app that has a text box where I can enter content, limited to 200 characters, into a database.

My goal is to list the items below the text box so that when a user enters something, it appears at the top of an ever-growing list.

Right now I have some crappy code that doesn't work, but I'm not sure why.

In my view page, located at home.html.erb, I have this area for the lessons to be viewed in:

<td class="my-lessons">

</td>

In my Lesson controller I have the following:

  def printLesson
    @lesson = Lesson.find(params[:id])

    puts @lesson.content
  end

I'm not sure how to call printLesson in my code and just generally how to show the content of the Lessons database.

Any help would be greatly appreciated

Upvotes: 1

Views: 647

Answers (1)

Soliah
Soliah

Reputation: 1406

home.html.erb gets rendered when you go to http://localhost:3000/lesson/home provided you have the appropriate route defined in routes.rb:

match 'lesson/home' => 'lesson#home'

So in your Lesson controller, in the home action have the following:

def home
  @lessons = Lesson.all
end

Now in your home.html.erb view render the contents of @lessons

<% @lessons.each do |lesson| %>
<tr>
    <td class="my-lessons">
      <%= lesson.Name %>
    </td>
</tr>
<% end %>

The problem you're having is thinking that you have to tell Rails to spit out the input in your controller action (the line puts @lesson.content). Rails works on convention. Any instance variables created in your controller's action will be accessible in your view. So the @lessons variable in the example above is accessible in the home.html.erb view.

I suggest having a read at the following for more info to do with routes and rendering views:

Upvotes: 3

Related Questions