Rails控制器设计:在同一视图上列出和创建
从 Rails 博客教程开始,我想在单个视图上列出并创建功能。但我不知道如何设计控制器来实现这一点。
索引视图必须显示简单的帖子列表和用于创建新帖子的表单。 我可以用部分解决这个问题吗?如何?我需要“新”和“创建”方法吗?仅仅创建还不够?
class MyPostsController < ApplicationController
def index
@posts = Post.all
end
def new
end
def create
end
end
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望在
index
视图中显示表单,请渲染该表单。我推荐部分,但这不是强制。根据表单实现,您可能需要一个新的Post
模型,这就像在index
操作中放置@post = Post.new
一样简单。create
可能不够“足够”的原因是某些表单是“用于”模型实例的。在这些情况下,通常new
操作会创建一个新的Post
并呈现表单,而create
操作实际上会保存(创建)它。If you want to have the form in the
index
view, render the form. I'd recommend a partial, but it's not mandatory. Depending on the form implementation you may need a newPost
model, that's as easy as putting a@post = Post.new
in theindex
action.The reason
create
may not be "enough" is because some forms are "for" an instance of the model. In those cases generally thenew
action makes a newPost
and renders the form, whereas thecreate
action actually saves (creates) it.