1

Note that User has many Photos. I'm using the friendly_id gem to generate a slug for photos. This is my Photo model:

class Photo < ActiveRecord::Base
  extend FriendlyId
  friendly_id :photo_by_author, :use => :slugged

  def should_generate_new_friendly_id?
    title_changed?
  end

  def photo_by_author
    "#{title} by #{user_id}"
  end

  belongs_to :user
end

My path is profilename/photos/title, this is my routes.rb

scope ':profile_name' do
  resources :photos
end

In my controller, I'm doing @photo = Photo.all.

I'm trying this but isn't working: <a href="<%= photo %>">

How can I do the photos#show path??

Jimmy
  • 35,686
  • 13
  • 80
  • 98
Igor Martins
  • 2,015
  • 7
  • 36
  • 57

2 Answers2

1

Have you try

<% @photo.each do |photo| %>
<%= link_to photo.photo_by_author, photo %>
<% end %>

or

<a href=<%= photo %>" ><%= Photo.first.photo_by_author %></a
> 

inside the block

or in your console rails c -s

include Rails.application.routes.url_helpers
default_url_options[:host] = "localhost"
photo_url(Photo.first)
Papouche Guinslyzinho
  • 5,277
  • 14
  • 58
  • 101
0

Link_To

Firstly, you shouldn't be trying to populate a "naked" <a> with your ruby variable - you need to use the <%= link_to %> helper:

<%= link_to photo.title, photo_path(photo) %>

The problem is your scope, especially considering this scope is used to determine a variable. I believe the issue is that since Rails expects a variable from this scope, it will not be able to process any of the links without having it

The simple way to resolve that error, as mentioned in the comments,is to populate the route with both values:

<%= link_to photo.title, photo_path(profile_name, photo) %> #-> photo & profile_name need to be declared

You'll want to look up a rake routes to make this work


Friendly_ID

If you want to populate the friendly_id slug values for this route, you'll need to do two things:

  1. Pass the profile_name value as a "slug" (not ID)
  2. Pass the photo object itself

I noticed in the comments, Tiago Farias posted a possible solution for you. If you want that to work with friendly_id, you'll need to pass the photo object without defining the id attribute (this will let friendly_id work its magic)

The next thing you need to consider is that since :profile_name is not tied to any "resource" (controller / model), friendly_id won't be able to populate the name / value that you'd expect. In this case, you need to set the value yourself (by defining it explicitly in your controller)

Richard Peck
  • 76,116
  • 9
  • 93
  • 147