0

在PostController中的指標作用Ruby on Rails:如何從Post.paginate的用戶表中獲取用戶名?

@posts = Post.paginate(:per_page => 15, :page => params[:page], :order => 'created_at DESC') 

職位表

        Table "public.posts" 
    Column |   Type   |      Modifiers      
-------------+------------------------+---------------------------------------------------- 
id   | integer    | not null default nextval('posts_id_seq'::regclass) 
title  | character varying(100) | not null 
content  | character varying(500) | not null 
created_at | date     | 
updated_at | date     | 
tags  | character varying(55) | not null default '50'::character varying 
category_id | integer    | not null default 1 
user_id  | integer    | 
Indexes: 
    "posts_pkey" PRIMARY KEY, btree (id) 

用戶表

          Table "public.users" 
     Column   |   Type    |      Modifiers      
------------------------+-----------------------------+---------------------------------------------------- 
id      | integer      | not null default nextval('users_id_seq'::regclass) 
email     | character varying(255)  | not null default ''::character varying 
encrypted_password  | character varying(128)  | not null default ''::character varying 
reset_password_token | character varying(255)  | 
reset_password_sent_at | timestamp without time zone | 
remember_created_at | timestamp without time zone | 
sign_in_count   | integer      | default 0 
current_sign_in_at  | timestamp without time zone | 
last_sign_in_at  | timestamp without time zone | 
current_sign_in_ip  | character varying(255)  | 
last_sign_in_ip  | character varying(255)  | 
confirmation_token  | character varying(255)  | 
confirmed_at   | timestamp without time zone | 
confirmation_sent_at | timestamp without time zone | 
username    | character varying(255)  | not null 
is_admin    | boolean      | default false 
created_at    | timestamp without time zone | 
updated_at    | timestamp without time zone | 
Indexes: 
    "users_pkey" PRIMARY KEY, btree (id) 
    "index_users_on_confirmation_token" UNIQUE, btree (confirmation_token) 
    "index_users_on_email" UNIQUE, btree (email) 
    "index_users_on_reset_password_token" UNIQUE, btree (reset_password_token) 
    "index_users_on_username" UNIQUE, btree (username) 

我需要從用戶表的用戶名(需要加入),而不是從帖子USER_ID表。我已經使用在index.html.erb

分頁獲取用戶名我怎麼能顯示文章的index.html.erb用戶名

回答

4

只是簡單的包括應該做的伎倆:

@posts = Post.paginate(:per_page => 15, :page => params[:page], :order => 'created_at DESC', :include => :user) 

然後在視圖中:

post.user.username 
+0

非常感謝。但是有沒有其他辦法可以做同樣的事情?這是如何包括工作的?如果我使用`Post.find`,那麼我如何獲得用戶名? – shibly 2011-12-16 10:45:53