views:

142

answers:

1

I have a user model and a profile model.

user has_one :profile profile belongs_to :user

Because of this relationship, I pull up my profiles by calling the user id. So my urls look like this: website.com/users/[user_id]/profile

I'm not sure if there's a solution to my problem. Here it is: I would like to display SEO friendly urls. I'm looking at using friendly_id for this. But, our profiles are for businesses, and it's the business name that we want to put in the url. The problem is that our user model intentionally does not ask for the business name, and it's the user_id that gets displayed in the url currently.

Is there a way to grab the business name from the profile model (i.e. @profile.name), and use it to populate the [user_id] part of the url?

UPDATE: I've set up the friendly_id gem and it seems like this could work. In my profile model, I have this: has_friendly_id :name, :use_slug => true

When I updated a profile, friendly_id did slugify the url by putting the business name from the profile into the user_id part of the url. But, of course, this threw an exception.

So if the the business name in the profile model is Mike's Bar, the url now says /users/mike-s-bar/profile. The exception says this: Couldn't find User with ID=mike-s-bar.

Here's my profiles controller:

def show
  @user = User.find(:all)
  @profile = User.find(params[:user_id])
end

Is there a way to make this work?

A: 

Hmm, does a Business have multiple users? If so, how can /users/xzy/profile then be unique?

Otherwise: I don't think that friendly_id can handle columns outside of the models table. However here an approach I would try:

class User

  # used by rails to generate URLs - defaults to ID
  def to_param
    "#{self.id}-#{self.business.name}"
  end

  ...
end

The find method skips everything behind a dash by itself. This would cause your URLs to be a little bit less readable: /users/xzy/profile will become /users/7-xzy/profile which is quite similar to how SO does it.

Marcel J.
I second this, but would add a call to parameterize:<pre><code>def to_param "#{id}-#{business.name.parameterize}"end</code></pre>You want to keep the <id> in the URL since we are sure it uniquely identifies your users.
hgimenez