gpt4 book ai didi

ruby-on-rails - Ruby on Rails : How can i get the username from users table with Post. 分页?

转载 作者:行者123 更新时间:2023-11-29 14:12:36 25 4
gpt4 key购买 nike

在 PostController 的索引 Action 中

@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)

我需要从 users 表中获取用户名(需要加入),而不是从 posts 表中获取 user_id。我在 index.html.erb 中使用了分页

获取用户名 如何在 index.html.erb 中显示帖子的用户名

最佳答案

只需简单的包含就可以解决问题:

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

然后在 View 中:

post.user.username

关于ruby-on-rails - Ruby on Rails : How can i get the username from users table with Post. 分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8532875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com