How to change on a table A, the name of 1 column, depending on the id of the table B

hi… i’m new on rails… i have 2 tables, “clientes” (belongs_to :store), and “stores” (has_many :clientes)… when i show the records saved on clientes table, the query gives me a table with these columns: name, last_name, email, AND store_id … what i want to do it’s that instead of the number of the store_id, it shows me the ]“name” of the store with the id shown on the table (the table stores ahve the fields id, name, address, etc…)

on clientes_controller i have
def index @clientes = Cliente.all @stores = Store.all end

/// I made these lines just to test but it gives me 1 fixed name (the first one in the stores table), it does not change according to the id ///

        <% @stores.find(cliente.store_id) do |store| %>
      <td><%= store.nombre %></td>
        <% end %>`

Preformatted text


the table on index.html.erb:

<% @clientes.each do |cliente| %>
        <% @stores.find(cliente.store_id) do |store| %>
      <td><%= store.nombre %></td>
        <% end %>

    <td><%= link_to 'Show', cliente %></td>
    <td><%= link_to 'Edit', edit_cliente_path(cliente) %></td>
    <td><%= link_to 'Destroy', cliente, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
Nombre Apellido Rut Email Store
<%= cliente.nombre %> <%= cliente.apellido %> <%= cliente.rut %> <%= %> <%= cliente.store_id %>

If you want to use find it doesn’t take a block. But the better way would be to use the relationships you setup. So:

<td><%= %></td>

If some clients may have no store (i.e. the belongs_to has an optional flag) then you need to handle that as well. You can do that via the safe navigation operator:

<td><%= %></td>

Or you can define a delegate attribute in your client model and use that. So in your Cliente model you might have:

belongs_to :store, optional: true

delegate :nombre, to :store, prefix: true, allow_nil: true

Then in your view you just have:

<td><%= cliente.store_nombre %></td>
1 Like

thank you !!!.. it works great!!!