问题描述
我遵循了 rails 3 教程,我正在努力使其正常工作.
I followed a rails 3 tutorial and I'm trying to get this to work correctly.
用户发布的所有微博都列在http://localhost:3000/users/username
All microposts that a user make is listed in http://localhost:3000/users/username
用户控制器
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
(如果有效)之类的链接将指向只有该微博的页面?
How can I set it up so that a link such as http://localhost:3000/users/username/micropost_id
(if valid) will lead to page that has just that micropost?
除了在新页面上单独显示之外,我希望显示完全相同.
I want the display to be exactly the same except show up individually on a new page.
用户表
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
推荐答案
你应该在你的 routes.rb 文件中添加一个新的路由,如下所示:
You should add a new route to your routes.rb file like the following:
match '/users/:username/:id', to 'microposts#show', via: :get, as: :user_micropost
在显示用户微博的页面上,将链接添加为:
and on the page that shows user's microposts, add the link as:
<a href="<%= user_micropost_path(username: @user.username, id: micropost.id) %>">Whatever..</a>
在 microposts 控制器上,添加 show 方法:
On the microposts controller, add the method show:
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
将显示微博的新页面.
这篇关于如何显示单个微博的链接?(ruby on rails 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!