Phoenix Web Development
上QQ阅读APP看书,第一时间看更新

Grabbing a list of data

We'll build a function that can provide a simple interface to get the data out of the system and to our controllers. So what do we want here? We want a simple function that is going to return an array of data (in our case, Polls). Of course, we'll also want to preload the Options for those Polls as well. The good news is that writing functions for our interfaces is just as simple as writing functions in Elixir! Let's take a look at our first example:

 def list_polls do
Repo.all(Poll) |> Repo.preload(:options)
end

All we've done here is written a single line of code, and yet this is also the code that will give us access to our Poll and Option data! Now, when we want a list of Polls, we don't need to think about having multiple schemas to interact with or multiple files to deal with; it's just one simple interface!

Okay, so we're talking a lot about how great it is that we've made this simple interface; let's actually put it into action! Before we move on any further, though, we should likely spend a few minutes talking about how to actually write queries in Ecto, as you may be doing quite a bit of that and it will be very important to understand exactly how to get data out of the database and into data structures that Elixir can properly interpret.