2011-10-11 1 views
0

난 레일에 대해 friendly_id에 빨간색 문서가 있습니다. 쉽습니다. 특정 속성을 슬러그로 설정했습니다.사용자 모델의 username과 함께 friendly_id를 사용하여 example.com/profiles/1을 example.com/username으로 이동하려면 어떻게해야합니까?

User has_one profile 
Profile belongs_to User 

example.com/username 그래서 당신은 나의 딜레마를 참조하십시오. 프로필 모델에 열 사용자 이름이 없습니다. friendly_id로 example.com/username을 할 수 있도록 사용자 모델, 사용자 이름 필드를 어떻게 연결할 수 있습니까?

확실히 비교적 간단합니다.

def show 
    @user = User.joins(:profile).where("profiles.username = ?", params[:username]) 
end 

경로 : 당신의 ProfilesController#show에서

답변

2

당신은 당신의 루트 파일의 마지막에 "캐치 올"경로를 사용할 수 있습니다

map.connect ':username', :controller => 'profiles', :action => 'show' (this is for Rails 2.3) 

그리고 프로파일 컨트롤러, 방법은 해당 사용자 이름을 가진 사용자가있는 경우 확인할 보여주고, 경우 그것은 현재 프로파일에 속합니다.

def show 
    if User.find_by_username(params[:username]) 
    if @current_user == User.find_by_username(params[:username]) 
    # @profile = @current_user.profile 
    # render projects#show view 
    else 
    # flash error message, because the current user tries to access other users profile (in case your app doesn't allow it) 
    else 
    # render page not found error 
    end 
end 

프로젝트/id =>/project_name에서 비슷한 상황이있었습니다. db에 고유 한 사용자 이름이 있기 때문에 약간 더 쉽습니다. 아, 여분의 보석이 포함되어 있지 않습니다.

1

class User < ActiveRecord::Base 
    def fetch_by_username(username) 
    joins(:profile).where("profiles.username = ?", username) 
    end 
end 

그리고 지역 :

match ':username' => "profiles#show' 

선택적으로, 컨트롤러 청소기를 만들기 위해 사용자 모델에 메서드를 추가 할 수 있습니다 귀하의 컨트롤러 :

@user = User.fetch_by_username(params[:username]) 
+0

프로필 모델 내에 @ profile.firstname이있는 프로필보기가 있습니다. 사용자 이름이 없으므로 회신 해 주셔서 감사합니다. 테이블 사용자는 id와 비슷합니다 | user_id | etc 프로필 테이블은 같습니다. | id | user_id | etc – Rubytastic

+0

위의 예제를 시도했는데 모두 작동하지 않습니다. 내 프로필 테이블에 사용자 이름 열이 없습니다. user_id 사용자에게 속한 것입니다. 여분의 보석을 추가하는 대신 기본 라우팅을 사용하면됩니다. 아직도 실제 해결책을 찾지 못했을 수도 있습니다. – Rubytastic

1

사용자 정의 방법을 사용하여 필요한 슬러그를 생성 할 수 있습니다.

class Profile < ActiveRecord::Base 
    has_many :users 

    has_friendly_id :custom_url_method, :use => :slugged 

    def custom_url_method 
    self.user.username.to_url 
    end 

to_url은 Stringex gem입니다. 또는 Friendly_id 자체에서 제공하는 Babosa의 헬퍼 메소드 중 하나를 사용할 수 있습니다.

+0

당신은 Friendly_id 자체가 제공하는 Babosa의 헬퍼 메소드 중 하나를 사용할 수도 있습니다. 어떤 도우미가 될 수 있을까요? – Rubytastic

+0

' "Gölcük, Turkey".to_slug.normalize.to_s # => "골쿨 칠면조"' https://github.com/norman/babosa에서 예제를 확인할 수 있습니다. – membLoper