Get user.username based on item.user_id?

Hey,

I have this code:

<h1><%= @item.title %></h1>

<ul>
  <li><strong>Description:</strong> <%= @item.description %></li>
  <li><strong>Auction ends at:</strong> <%= formatted_datetime(@item.ends_at) %></li>
  <li><strong>Owner:</strong> **<%= inspect @item.user_id %>**</li>
</ul>

@item.user_id is returning user_id (belongs_to users), but how could I get the username of that user?

<%= inspect @item.user_id.username %> gives me an argument error.

You need to preload user for item… then You might access user properties directly like item.user.username

You can also load the user from item.user_id and pass it as part of assigns.

It seems like I’m doing something wrong, still get an argument error.

  def list_items do
    item = Repo.all(Item) |> Repo.preload([:user])
  end

  def get_item(id) do
    @repo.get!(Item, id) |> Repo.preload([:user])
  end

schema

  schema "items" do
    field :title, :string
    field :description, :string
    field :ends_at, :utc_datetime
    belongs_to :user, Auction.User
    has_many :bids, Auction.Bid

  timestamps()
  end

Those are my first steps in Phoenix…

Once it’s preloaded switch to the relationship name. So @item.user.username

2 Likes

Thank You!