Bitwise
Bitwise

Reputation: 8461

Query for an ID on a record - Phoenix and Elixir

I'm coming from a rails background (like many Elixir folks). My current problem is that I'm trying to query for a particular record. This is a no brainer in rails for me but I can't seem to figure it out in Phoenix. Here is what I'm trying to do:

I have a Location table that has_many Monitors and a Monitor has a number that is not an ID. These number are only unique to a Location so I can't simply find particular monitor with just the monitor number. So I have to scope it to the Location it belongs to. In Rails I would do something like this:

location = Location.find(params[:location_id])

monitor = location.monitors.find_by(number: params[:monitor_number])

Easy peasy with Rails active record but How can I do this with Phoenix? Here is my current attempt that is not working as I expect.

monitor_query = from m in Monitor,
  where: m.location_id == ^upload_params["location_id"],
  where: m.number == ^upload_params["monitor_number"],
  select: m.id

monitor = Repo.all(monitor_query)

That is pulling up the wrong ID and I'm not sure what its doing. Can anyone tell help me out with this?

Upvotes: 1

Views: 538

Answers (1)

Dogbert
Dogbert

Reputation: 222398

The most straightforward conversion of that Rails code would be this:

location = Repo.get(Location, params["location_id"])
monitor = Repo.get_by(Ecto.assoc(location, :monitors), number: params["monitor_number"])

Ecto.assoc(location, :monitors) returns a query that's basically from m in Monitor, where: m.location_id == ^location.id. We then add more constraints to it (where: m.number == ^params["monitor"]) and fetch that record using Repo.get_by.

Upvotes: 5

Related Questions