Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Render Form on Index

I want to be able to use <%= render 'form' %> on the index page. Is this the correct way to go about that? It appears to work, however, I just want to ensure this is the correct method of doing this.

class RemindersController < ApplicationController  
... 
    def index
      @reminders = Reminder.all
      @reminder = Reminder.new 
    end
....
like image 645
JeremyE Avatar asked Sep 30 '22 06:09

JeremyE


1 Answers

There is nothing wrong with including the 'new'/'edit' form in the index view. It's not the 'normal' Rails way but it will work. Remember, once you filled out your form on the page, you still need to submit that form (you can only submit one at a time). This is where it kinda gets tricky. If you want to create and update reminders from the same page, you must have different forms with different actions. The 'new' form would look like:

<%= form_for @reminder, url: {controller: "reminders", action: "create"} do |r| %>
  <form code goes here>
  <%= r.submit %>
<% end %>

and the 'edit' form(s) would be something like:

<%= @reminders.each do |reminder| %>
  <%= form_for reminder, url: {controller: "reminders", action: "update"} do |r| %>
    <form code goes here>
    <%= r.submit %>
  <% end %>
<% end %>

EDIT

If you want the entire form inside the _form.html.erb partial, you can also pass in the url as a paramater, like this:

<%= render partial: 'form', locals: {path: {controller: "reminders", action: (create/update)}} %>

and then inside your partial:

<%= form_for @reminder, url: path %>
like image 116
Ryan K Avatar answered Oct 03 '22 09:10

Ryan K