简体   繁体   中英

How do I structure rails 3 controllers and views for ajax based applications

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 - ie 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

and then create a posts/body sub controller:

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

The url for this will be:

/posts/:post_id/body

Which to me looks right.

Does anyone else have any better ideas?

Good question. I have an application that serves ajax requests as well as regular page requests and I went with your first approach of putting the ajax action in the body of the resource controller.

Personally I like this approach better because it keeps the controllers manageable. With your second idea of creating it as a nested resource you end up having a lot of controllers that just perform a single ajax action. I would prefer I high cohesion solution where everything about Posts is done in the PostsController vs. creating lots of single action sub controllers.

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

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 ).

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM