title: Writing Fragments for Polymorphic Associations in RelayJS and GraphQL
body: <p>My backend schema has a model, <code>Request</code>, that uses a polymorphic association such that several different models all have-many Requests and a <code>Request</code> can belong to any one of those different models.</p>
  
  <p>I've got a React Component, <code>RequestList</code>, that I want to be able to use in any of it's potential parent models.</p>
  
  <p>Here's some sample code:</p>
  
  <p>FooShowView.js</p>
  
  <pre><code>class FooShowView extends Component {
    render() {
      return (
        &lt;RequestList router={this.props.router} /&gt;
      )
    }
  }
  
  export default Relay.createContainer(ShowView, {
    initialVariables: {
      FooId: null
    },
    fragments: {
      viewer: (variables) =&gt; {
        return Relay.QL`
          fragment on Viewer {
            Foo(id: $FooId) {
              id${ RequestList.getFragment('Foo') }
            }
          }`
        `
      }
    }
  });
  </code></pre>
  
  <p>RequestList.js</p>
  
  <pre><code>class RequestList extends Component {
  
    renderRows = () =&gt; {
      return this.props.requests.edges.map(edge =&gt; edge.node).map((intReq, i) =&gt; {
        return (
          &lt;RequestRow
            request={ intReq }
            key={ i }
          /&gt;
        );
      });
    }
  
    render() {
      return (
        &lt;Table&gt;
          { this.renderRows() }
        &lt;/Table&gt;
      );
    }
  };
  
  export default Relay.createContainer(RequestList, {
    fragments: {
      foo: () =&gt; Relay.QL`
        fragment on Foo {
          requests(first: 10) {
            edges {
              node {
                ${ RequestRow.getFragment('request') }
              }
            }
          }
        }
      `,
    }
  })
  </code></pre>
  
  <p>The problem is that now to render the RequestTable for another one of <code>Request</code>'s parents, say in the <code>BarShowView</code>, I'd need to add a new fragment to <code>RequestList</code>:</p>
  
  <pre><code>bar: () =&gt; Relay.QL`
    fragment on Bar {
      requests(first: 10) {
        edges {
          node {
            ${ RequestRow.getFragment('request') }
          }
        }
      }
    }
  `,
  </code></pre>
  
  <p>And then Relay will spit out warnings that I need to provide both bar and foo as props to my List, even if it's not relevant to the current view.</p>
  
  <p>Since <code>Request</code> is associated with roughly 8 different models in my schema, this will quickly become unreasonable.</p>
  
  <p>What is the correct way to create a reusable react component that will render the polymorphic children of whatever record I'm looking at?</p>