starting from the rails blog tutorial, i want to have listing and create functionality on a single view. But i don’t known how to design the controller to accomplish this.
The index view must show a simple list of posts and a form to create a new post.
Can i solve this with partials? How? I need a “new” and “create” methods? With only create is not enough?
class MyPostsController < ApplicationController
def index
@posts = Post.all
end
def new
end
def create
end
end
If you want to have the form in the
indexview, render the form. I’d recommend a partial, but it’s not mandatory. Depending on the form implementation you may need a newPostmodel, that’s as easy as putting a@post = Post.newin theindexaction.The reason
createmay not be “enough” is because some forms are “for” an instance of the model. In those cases generally thenewaction makes a newPostand renders the form, whereas thecreateaction actually saves (creates) it.