2013-04-17 52 views
1

我跟着一個rails 3教程,我試圖讓這個工作正常。如何顯示個別微博的鏈接? (在軌道3上的紅寶石)

,用戶提出的是在http://localhost:3000/users/username

UsersController中列出的所有微柱

def show 
    @user = User.find(params[:id]) 
    @microposts = @user.microposts.paginate page: params[:page], :per_page => 15 
    end 

每個微柱都有一個ID

create_table "microposts", :force => true do |t| 
    t.text  "content" 
    t.integer "user_id" 
    t.datetime "created_at",       :null => false 
    t.datetime "updated_at",       :null => false 
    t.string "image" 
    t.text  "comment_content" 
    end 

我如何設定,讓這樣的鏈接http://localhost:3000/users/username/micropost_id(如果有效)將導致只有該微博的頁面?

我希望顯示完全一樣,除了在新頁面上單獨顯示。

用戶表

create_table "users", :force => true do |t| 
    t.string "name" 
    t.string "email" 
    t.timestamp "created_at",       :null => false 
    t.timestamp "updated_at",       :null => false 
    t.string "password_digest" 
    t.string "remember_token" 
    end 

我的配置路線

MyApp::Application.routes.draw do 
    resources :authentications 

resources :microposts, :path => "posts" 


root to: 'static_pages#home' 

      ActiveAdmin.routes(self) 


    resources :users do 
    member do 
     get :following, :followers 
    end 
    end 
    resources :sessions, only: [:new, :create, :destroy] 
    resources :microposts, only: [:create, :destroy] 
    resources :relationships, only: [:create, :destroy] 
    resources :microposts do 
    resources :postcomments 

end 


    match '/signup', to: 'users#new' 
    match '/signin', to: 'sessions#new' 
    match '/signout', to: 'sessions#destroy', via: :delete 

    match '/post', to: 'static_pages#post' 
    match '/about', to: 'static_pages#about' 
    match '/contact', to: 'static_pages#contact' 
    match '/users/:username/:id', to: 'microposts#show', via: :get, as: :user_micropost 
end 
+0

你可以發佈你的'config/routes'嗎? – everett1992

+0

posted routes.rb – nextstep

回答

0

您應該添加一個新的路由到您的routes.rb文件類似如下:

match '/users/:username/:id', to 'microposts#show', via: :get, as: :user_micropost 

,並在頁面上顯示用戶的微博,添加鏈接爲:

<a href="<%= user_micropost_path(username: @user.username, id: micropost.id) %>">Whatever..</a> 

在微柱控制器,添加方法顯示:

def show 
    @user = User.find_by_username(params[:username]) 
    @post = Post.find_by_id(params[:id]) 
    # handle any errors from the code above 
end 

,並創造條件,

app/views/microposts/show.html.erb 

新頁面將顯示在微柱。

+0

我得到一個'無法找到id = 260的用戶...我怎麼能改變它來搜索Micropost_Id ..不是用戶ID?我更新了用戶架構的原始帖子 – nextstep

+0

您是如何在顯示所有帖子的頁面中添加鏈接的?在你的控制器的「show」方法中,你應該通過params [:id]和用戶名通過params [:username]得到微博的id。你可以發佈生成的鏈接的來源,看看它指向哪裏? –

+0

其實我有它的工作。在剛剛在microposts文件夾中創建的新'show.html.erb'中,我必須自己創建視圖嗎?我如何才能參考那個特定的micropost內容,micropost用戶等來展示? – nextstep

0

我在你的路由猜你有提到這樣的事情

resources :users do 
    resources :microposts 
end 

在這種情況下,你可以在你的/views/users/show.html.erb創建鏈接,這樣的事情

<% @microposts.each do |post| 
    <%= link_to truncate(post.content, :length => 10, :separator => '...'), user_micropost_path(@user, post) %> 
<% end %>