如何为基于 ajax 的应用程序构建 Rails 3 控制器和视图 [英] How do I structure rails 3 controllers and views for ajax based applications

查看:40
本文介绍了如何为基于 ajax 的应用程序构建 Rails 3 控制器和视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为基于 ajax 的 Rails 应用程序构建控制器和视图的最佳实践是什么.

I was wondering what best practices are for structuring the controllers and views for ajax based rails applications.

例如,如果我有一个由帖子组成的博客,并且我希望能够动态刷新帖子正文,我将如何构建我的应用程序来执行此操作.

For example if I had a blog, which is made up of posts and I wanted to be able to dynamically refresh a post body how would I structure my application to do this.

从技术上讲,你只应该在控制器中有动词 - 即动作或做词.这意味着执行以下操作将是错误的:

Technically you're only supposed to have verbs in the controller - i.e. actions or doing words. This means doing the following would be wrong:

class PostsController < ApplicationController
    #...
    def body
        #return body of a particular post
    end
    #...
end

所以我的另一个想法是将其创建为嵌套资源:

So my other idea is to create it as a nested resource:

resources :posts do
    resource :body, :controller = "posts/body"
end

然后创建一个posts/body子控制器:

and then create a posts/body sub controller:

class Posts::BodyController < ApplicationController
    def show
        #return body of a particular post
    end
end

此网址将是:

/posts/:post_id/body

/posts/:post_id/body

哪个在我看来是正确的.

Which to me looks right.

其他人有更好的想法吗?

Does anyone else have any better ideas?

推荐答案

为什么只需要正文?为什么不返回整个帖子并只使用正文?

Why do you need just the body? Why don't you return the entire post and just use the body?

如果这还不够好,你可以做这样的事情

If that's not good enough you could do something like this

def show
  @post = Post.find(params[:id])

  # set some etag stuff up so we don't have to request this again if it hasn't changed 
  response.last_modified = @post.created_at.utc
  response.etag = @post

  return head :not_modified unless request.fresh?(response)
  respond_to do |wants|
    wants.js { render :json => @post.to_json(:only => params[:select]) }
  end
end

以上代码可能存在一些问题.首先,如果 find() 返回一个可链接的查询,我不记得了,其次,为了安全起见,你应该清理 fields 所以它只返回一个字段的白名单(您可以使用 slice 执行此操作).

There are a few possible problems with this above code. Firstly, I can't remember off the top of my head if find() returns a chainable query, secondly, for safety you should probably sanitize fields so it only returns a white list of fields (you can do this with slice).

我希望这会有所帮助!

这篇关于如何为基于 ajax 的应用程序构建 Rails 3 控制器和视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆