Search code examples
ruby-on-railsdatabasehas-many

Rails: Resolve "has_many" only on demand


I'm using rails only as a backend to serve JSON data to the Ember frontend application.

My DB Structure is quite concatenated, what leeds to rails loading the complete database on every request.

How can i deal with that?

For example, I got a blog, blog "has_many" articles, articles "has_many" comments and so on. When I want to view a blog I don't care about the comments, all I need are the articles list.

So how can I prevent rails from resolving the "has_many" relationship on articles, when I don't need them?


Solution

  • i think i've found the sollution ... not sure if it's the best way, but it works ... i add some conditions to the controller, now it looks like:

    def index
        @offices = Office.all
        render json: @offices.as_json(
            only: [:id, :title, :created_at],
            include: { 
                addresses: { 
                    except: [:contacts] 
                } 
            }
        )
    end