参考字段属于Rails中的另一个模型类



我使用设计并将我的模型名称设置为用户。当我创建帖子模型时,我输入以下内容:

 rails g model Post title body:text user:references

在"帖子部分视图"的索引页面上,每当用户在用以下代码发布以下代码的帖子时,我都可以看到所有用户的ID号:

<div class="container-fluid">
<% @posts.each do |post| %>
<div class="row">
<div class="jumbotron">
      <div class="page-header">
        <h1><%= post.title %> <small>by: 
       <%= post.user_id %></small></h1>
      </div>
    </div>
</div>

我的帖子控制器类中的@posts变量是:

@posts = Post.all

基本上我要做的就是获取用户电子邮件。

在您的控制器中:

@posts = Post.includes(:user).all

在视图中:

post.user.email

建议:从长远来看

您只需通过模型即可获得关联的模型:

<%= post.user.email %>

最新更新