1

我遵循了 rails 3 教程,并试图让它正常工作。

用户发布的所有微博都列在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(如果有效)之类的链接将指向只有该​​微帖子的页面?

我希望显示完全相同,只是在新页面上单独显示。

用户表

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
4

2 回答 2

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>

在 microposts 控制器上,添加方法 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

将显示微博的新页面。

于 2013-04-17T21:02:52.697 回答
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 %>
于 2013-04-17T21:20:13.673 回答