Question

I'm trying to implement the Friendly_Id gem in my rails 4 app and have hit a roadblock.

The gem is working, but the url still isn't pretty. It looks like this:

http://www.example.com/project/featured?id=project-name

The gem is working because the id parameter is now a slug, however I have no idea how to remove the "?id=" and replace it with a slash? Is that possible? Did I miss a step?

Controller:

  def featured
    @project = Project.friendly.find(params[:id])
  end

Model:

  extend FriendlyId
  friendly_id :title, use: :slugged

View:

     <% @projects.each do |project| %>

        <%= link_to project_featured_path(:id => project.slug) do %>

            <%= project.title %>

        <% end %>

    <% end %>

Relevant Routes:

get "project/featured"

match 'project' => 'project#index', :as => :project, via: [:get, :post]

resources :projects do
  member do
    get :featured
  end
end

match ':controller(/:action(/:id))(.:format)', via: [:get, :post]   

I've also referenced a previous app of mine running Friendly_Id in rails 3. It doesn't seem to have this problem... can't remember if I'm just missing a step.

Any help would be greatly appreciated. Cheers!

Update:

After substituting:

project_featured_path(:id => project.slug)

for pearlshareteam answer:

project_featured_path(project)

my url looks a bit better but is still not working. It looks like this:

http://example.com/project/featured.project-one

there is a period instead of a slash. On testing I found that if I just replaced the dot with a slash the correct page is actually generated.

Is it just a problem with my link_to formatting?

Was it helpful?

Solution

The answer depends on your routes so it might be handy to post them as well but if they look like this:

resources :projects do
  member do
    get :featured
  end
end

I would hazard a guess that the syntax you want is:

project_featured_path(project)

I checkout out the friendly_id source and it seems that friendly_id overrides the active record 'to_param' method. This is called by the rails path/url helpers to construct urls from AR objects so will construct the url with the url slug.

Also see the finder methods in the source where it looks like friendly ID overrides the 'find' method. It first looks for a friendly id and if that fails it falls back to looking it up by the traditional id.

I think that should help or hopefully be a hint in the right direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top