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.


Source: ruby

Leave a Reply