Question

I want to use FriendlyId to achieve this localhost3000/users/edu/profile but I do not know how to do it! I have these models User and UserProfile

class User < ActiveRecord::Base
  has_one :user_profile, :dependent => :destroy
  extend FriendlyId
  friendly_id :name, :use => :slugged
end  

class UserProfile < ActiveRecord::Base
  attr_accessible :user_id, :name, :surname, :nickname
  belongs_to :user 
end

How do I load in name of User the name of UserProfile? and How do you update name of User when the name of UserProfile changes?

For the first I used

class User < ActiveRecord::Base
...

  def name
    if user_profile
      "#{user_profile.name}"
    end  
  end

But I can't make it change when I update or create a new Profile in UserProfile.

Using Ruby 1.9.3 and Rails 3.2.13.

Was it helpful?

Solution

If I understood it correctly, your problem is about sharing data between models, not about FriendlyId.

It seems delegate is your best bet here. It's a method in ActiveSupport that allows one model to expose another model's methods as their own.

class User < ActiveRecord::Base
  delegate :name, :name=, :to => :user_profile
end

Reference: http://api.rubyonrails.org/classes/Module.html#method-i-delegate

The reason to delegate both :name and :name= is that the former method allows you to read from that attribute (getter), while the latter allows you to write to it (setter).

Before making these changes you'll want to run a migration to remove the name field from the users table in the database, since from now on you'll be using the data in the other model.

rails g migration remove_name_from_users name:string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top