2013-05-15 1 views
0

이니까 localhost3000/users/edu/profile을 달성하기 위해 FriendlyId를 사용하고 싶지만 어떻게해야할지 모르겠다! 나는FriendlyId가

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 

가 어떻게 사용자 USERPROFILE의 namename에 넣기 이러한 모델 사용자 및 사용자 프로필을? UserProfile의 이름이 변경되면 어떻게 사용자 이름을 업데이트합니까?

은 처음 들어 나는
class User < ActiveRecord::Base 
... 

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

을 사용하지만 내가 업데이트하거나 사용자 프로필에서 새 프로필을 만들 때 변경할 수 없습니다.

Ruby 1.9.3 및 Rails 3.2.13을 사용합니다.

답변

0

제대로 이해했다면 문제는 FriendlyId가 아니라 모델간에 데이터를 공유하는 것입니다.

여기에 가장 좋은 방법은 delegate입니다. 한 모델이 다른 모델의 메서드를 자체 모델로 노출 할 수있게하는 ActiveSupport의 한 방법입니다.

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

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

위임하는 이유 모두 :name:name=은 (세터) 후자가 쓸 수있게하면서 전자의 방법은, 그 특성 (게터)로부터 판독 할 수 있다는 것이다 .

변경하기 전에 데이터베이스의 users 테이블에서 name 필드를 제거하기 위해 이전을 실행하고 싶습니다. 이후부터 다른 모델의 데이터를 사용할 것이므로이 항목을 사용하십시오.

rails g migration remove_name_from_users name:string 
+0

감사합니다. 나는 그 이름을 위임했고 그것은 효과가 있었다. :) – edudepetris

+0

니스, 잘 알고있다. :) – depa