B
B
bobanuk2014-11-20 15:02:59
Ruby on Rails
bobanuk, 2014-11-20 15:02:59

How to display category name instead of category_id in index.html.erb ?

Hello everyone, please help. I make categories related to products, everything works fine, but I can’t figure out how to display the category name and not its id.

rails g scaffold Products name:string category_id
rails g scaffold Category name:string

product.rb
belongs_to :category

category.rb
has_many :products

index.html.erb
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Category</th>
      <th colspan="2"></th>
    </tr>
  </thead>

  <tbody>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= product.category_id %></td>
        <td><%= link_to 'Show', product %></td>
        <td><%= link_to 'Edit', edit_product_path(product) %></td>
        <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

products_controller.rb
def create
    product = Product.new(product_params)
    respond_to do |format|
      if product.save
        format.html { redirect_to product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

def new
    product = Product.new
    @categories = Category.all.map{|c| [ c.name, c.id ] }
end

_form.html.erb
<div class="field">
    <%= f.label :category_id %><br>
    <%= f.collection_select :category_id, Category.order(:name), :id, :name, class: 'span12' %>
  </div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Any1, 2014-11-20
@bobanuk

Instead
put
<td><%= product.category.name %></td>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question