1

나는 사용자가 게시물을 만들고, 다른 사용자를 따르고, 사용자가 따르는 모든 게시물의 피드를 가지고있는 작은 트위터 복제 앱을 만들었습니다. 게시물에 대한 범주 선택을 "스릴러" "서양" "공포"등으로 추가했습니다.레일 3 : 라우트/컨트롤러에 대한 레일 초보자 혼동

사용자가 로그인하면 루트 웹 주소가 대시 보드입니다. 사용자의 피드의 위치

routes.rb 

root :to => "pages#home" 

그리고 페이지 # 가정은 다음과 같습니다 @feed_items의 = 지금

PagesController 

def home 
    @title = "Home" 
    @featured_posts = Post.featured.limit(10) 
    if user_signed_in? 
     @user = current_user 
     @post = current_user.posts.build 
     @feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page]) 
    end 
end 

을 current_user.feed 내가 피드를 구문 분석하고 일부 공급을 당겨하는 방법을 알아 냈어요 그 CATEGORY_ID 만 게시물을 포함 '2'는 사용자 로그인

@thriller_feed_items= current_user.feed.where(:category_id => '2') 

는 그들의 대시 보드 및 전체 피드를 볼 수있는 root_path에 간다 (또한 '스릴러'로 알고있다). 현재 '@feed_items'를 @thriller_feed_items로 변경하는 '스릴러'라는 링크가 있기를 원합니다.하지만 경로와보기가 어떻게 작동하는지 혼란 스럽습니다. Twitter는 /! #/멘션을 하위 집합 피드의 주소로 사용하므로 동일한 작업을 수행해야합니까? 내가 어떻게 세울거야?

편집 : 내 피드 방법 작동 방식을 보여줍니다.

사용자 모델

def feed 
    Post.from_users_followed_by(self) 
    end 

포스트 모델

def self.followed_by(user) 
     followed_ids = %(SELECT followed_id FROM relationships 
         WHERE follower_id = :user_id) 
     where("user_id IN (#{followed_ids}) OR user_id = :user_id", :user_id => user) 
    end 

답변

2

이 컨트롤러는 비 RESTful 컨트롤러라고 가정합니다.

편집 : 범주 이름을 허용하도록 업데이트했습니다. 경로와 변수 색인을 적절히 조정하십시오.

경로.

match "/category/:category" => "pages#home" 

페이지 # 홈

def home 
    @title = "Home" 
    @featured_posts = Post.featured.limit(10) 
    if user_signed_in? 
    @user = current_user 
    @post = current_user.posts.build 
    # BEGIN NEW 
    if params[:category] 
     # is :category an integer id? 
     if params[:category].to_i.to_s == params[:category] 
     @feed_items= current_user.feed.where(:category_id => params[:category]) 
     else 
     # assuming Category has_many :feeds 
     @feed_items= current_user.feed.includes(:category).where(
      ['`categories`.name = ?', params[:category]] 
     ) 
     end 
    else 
     @feed_items = current_user.feed 
    end 
    @feed_items = @feed_items.paginate(:per_page => "10", :page => params[:page]) 
    # END NEW 
    end 
end 

보기 경우 rb :

<%= link_to "Thriller Feed Items (by id)", "/category/2" %> 
<%= link_to "Thriller Feed Items (by name)", "/category/Thriller" %> 
+0

안녕하세요, 저는이 솔루션을 정말 좋아하지만 어떻게 "/ category/스릴러"가 될 수있는 경로를 얻겠습니까 ??? 다시 한 번 감사드립니다. –

1

은 왜 당신은 스릴러라는 새로운 컨트롤러 액션 및 페이지/thriller.html라는 새로운 뷰를 생성하는 페이지 컨트롤러를 사용 해달라고. erb.

get 'page/thriller' 

또는 더 일반적으로

match 'thriller' => 'page#thriller' 

, 당신은 장르 액션을 작성하고 ID로 장르를 전달할 수 있습니다 : 당신의 routes.rb에서

, 당신은 다음과 같은 일을 할 수 있습니다.

match 'genre/:genre_id' => 'page#genre' (you get the parameter with params[:genre_id]) 

또한 routing guide을 읽었다.

+0

일을 권장 읽기. 기본적인 작업 방법을 이해하는 것 외에도 리소스를 중첩하고 '레이크 경로'를 활용하는 방법을 알고 있으면 삶이 편하게됩니다. – Tass