如何使用 `respond_to` 和 `respond_with` 执行多个操作?
我有一些视图,控制器操作如下所示:
def active
@posts = current_user.posts
respond_to do |format|
format.html{ render :template => "posts/list" }
format.js { render :template => "posts/list.js" }
end
end
我总是想为 PostsController 中的许多操作渲染上面的这些模板。
我不知道如何继续。
我正在寻找类似的东西:
class PostsController
respond_to :html, :js
def active
@posts = current_user.posts
#respond with the appropriate template (posts/list.html.erb or (posts/list.js.erb):
respond_with(....what goes here...??)
end
end
I have a few views and the controller actions look like this:
def active
@posts = current_user.posts
respond_to do |format|
format.html{ render :template => "posts/list" }
format.js { render :template => "posts/list.js" }
end
end
I always want to render those templates above for a lot of the actions in the PostsController.
I'm at a loss how to proceed.
I'm looking for something like:
class PostsController
respond_to :html, :js
def active
@posts = current_user.posts
#respond with the appropriate template (posts/list.html.erb or (posts/list.js.erb):
respond_with(....what goes here...??)
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你处理这个问题的方式是错误的。您应该做的第一件事就是坚持使用 RESTful 资源。因此,请删除
Posts
控制器上的active
方法。相反,请将Post
资源嵌套在您的User
下。因此,在您的路线中执行此操作这将为您提供类似于
/users/:user_id/posts
的路线,您可以使用user_posts
从视图中访问它,然后创建适当的 找到所需的所有信息。
html、js 等的视图。您将在此处 你指出了正确的方向。
I think you're going about this the wrong way. The first thing you should do is stick to RESTful resources. So get rid of your
active
method on yourPosts
controller. Instead, nest thePost
resource under yourUser
. So do this in your routesThis will give you routes that look like this
/users/:user_id/posts
and you can access it from your views usinguser_posts
Then create the appropriate views for html, js, etc. You'll find all the info you need here
Hopefully this gets you pointed in the right direction.