Answer the question
In order to leave comments, you need to log in
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
<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>
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
<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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question