Dipet
Dipet

Reputation: 323

Interpolating data in a rails view

I'm a beginner at rails and thus far interplating data in views has been pretty straight forward. I've been introduced to something slightly new as far as how the controllers are setup and as a result I'm not sure how one would go about getting the data to present in the view.

First controller

class PagesController < ApplicationController

  def index
    @guestbook_entry = GuestbookEntry.new
    render "welcome"
  end
end

Second controller

class GuestbookEntriesController < ApplicationController

  def create
    GuestbookEntry.create(guestbook_entry_params)
    redirect_to root_path, notice: "Thank you for your entry."
  end

  private

  def guestbook_entry_params
    params.require(:guestbook_entry).permit(:body)
  end
end

And here is the welcome.html.erb

<h1>Welcome to My Guestbook</h1>
<br>
<%= image_tag("under_construction.gif") %>

<div id="guestbook-entries">
  <p>Guestbook Entries:</p>
  <ul>
  </ul>
</div>

<%= form_for @guestbook_entry do |f| %>
  <%= f.label :body, "Guestbook Entry:" %>
  <%= f.text_area :body %>
  <%= f.submit "Submit" %>
<% end %>

So it wants me to iterate through all the entries and display them on a welcome page that's located in view/pages/welcome.html.erb.

Up to this point I guess I've only been doing basic simple rails applications where the view corresponded with the controller, and followed the typical CRUD setup, where index would hold the @xxx = Xxxx.all and new/create would handle @xxx = Xxxx.new/create/build. I thought I could simply move the PageController's index action to create/new and do

def index
  @guestbook_entry = GuestbookEntry.all
  render "welcome"
end

To satisfy the test (it looks for render welcome in the index action)

This seems weird but again I admit, I'm a beginner.

Upvotes: 1

Views: 270

Answers (1)

max
max

Reputation: 102036

If you want to list all the guest book entries on your root page you would do something like:

class PagesController < ApplicationController
  def index
    @guestbook_entry = GuestbookEntry.new
    @guestbook_entries = GuestbookEntry.limit(10).all
    render "welcome"
  end
end

And in your view you would list them like:

<% if @guestbook_entries.any? %>
<div id="guestbook-entries">
  <p>Guestbook Entries:</p>
  <% @guestbook_entries.each do |entry| %>
  <ul>
    <li class="entry"><%= h(entry.body) %></li>
  </ul>
  <% end %>
</div>
<% end %>

The rest of you application is correct - you should be creating entries in GuestbookEntriesController#create. In many real life applications then the functionality of the standard new and edit actions can actually be a totally different controller.

Upvotes: 1

Related Questions