I’ve been trying for the past 2 days but ultimately failed. I would like to get a URL like this: dresses/type/flower-girl but all I’ve got is /dresses/type/4
I’ve got Shop has_many Dresses and Type has_many Dresses. In my Dress table, I’ve got type_id column which reference to the Type table.
This is my code:
# Routes file
resources :dresses
match '/dresses/type/:id' => 'dresses#type'
# Type.rb model
extend FriendlyId
friendly_id :name, use: :slugged
# Dresses Controller
def index
@types = Type.all
end
def type
@dresses = Dress.find_all_by_type_id(params[:id])
end
# View (index.html.erb)
<% @types.each do |type| %>
<%= link_to type.name, :action => "type", :id => type.id %>
<% end %>
I’ve also tried using :name to replace :id in the routes, controller & view but they produced /dresses/type/Flower%20Girl instead.
What did I do wrong?
Alright, in your index view, change this
<%= link_to type.name, :action => "type", :id => type.id %>to<%= link_to type.name, :action => "type", :id => type.slug%>I suppose friendly_id doesn’t magically support custom routes, so you might end up looking for records by slug instead of id in your controller.