繁体   English   中英

如何显示各个微博的链接? (红宝石在轨道上3)

[英]how to display a link to individual microposts? (ruby on rails 3)

我遵循了Rails 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

您应该将新路由添加到您的route.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>

在微博控制器上,添加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

新页面将显示微博。

我想在您的路线中您提到过这样的事情

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 %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM