I created a guestbook that on one page displays both the form for a new entry and all of the entries that have been created so far.
I am trying to use Kaminari for pagination for the entries.
Right now this code is working on my local machine, but I just have that feeling that it could be improved/refactored, so I wanted to post it here for people's opinions.
My controller:
class GuestbooksController < ApplicationController
def index
@guestbooks = Guestbook.all
end
def new
@guestbook = Guestbook.new
@guestbooks = Guestbook.all
@guestbooks = Kaminari.paginate_array(@guestbooks).page(params[:page]).per(5)
end
def create
@guestbook = Guestbook.new(guestbook_params)
@guestbooks = Guestbook.all
@guestbooks = Kaminari.paginate_array(@guestbooks).page(params[:page]).per(5)
if @guestbook.save
flash.now[:notice] = "Thanks for taking the time to write us! We greatly appreciate it!"
render :new
else
flash.now[:notice] = "Your message failed to post, please try again"
render :new
end
end
private
def guestbook_params
params.require(:guestbook).permit(:name, :email, :message)
end
end
new.html.erb
template:
<div class="paginate">
<%=paginate @guestbooks%>
</div>
<div class="span1">
<% @guestbooks.each do |g| %>
<br/>
<h4><%= g.name %>, <%= g.created_at %><br/></h4>
<%= g.message %><br/>
<p>-----------------------------------------------------------------------------------------------------------------------</p>
<% end %>
</div>
<%= simple_form_for @guestbook, url: guestbooks_path, method: :post do |f| %>
<div class="span2"><%= f.input :name %></div>
<div class="span2"><%= f.input :email %></div>
<div class="span3"><%= f.input :message %></div>
<div class="span4"><%= f.button :submit %></div><br/><br/><br/>
<% end %>
Routes:
resources :guestbooks, only: [:new, :create]
get "/guestbooks/index", to: "guestbooks#index"
Now I know my routes file could look like this
resources :guestbooks, only: [:new, :create, :index]
but then my paths look strange:
guestbooks GET /guestbooks(.:format) guestbooks#index
POST /guestbooks(.:format) guestbooks#create
new_guestbook GET /guestbooks/new(.:format) guestbooks#new