简体   繁体   English

Rails外键混乱

[英]Rails foreign key confusion

I'm trying to learn rails. 我正在尝试学习Rails。 I have 2 tables Users and Posts, I want to link the email address from Users to Posts but I'm not sure how to go about it. 我有2个表“用户和帖子”,我想将“用户”的电子邮件地址链接到“帖子”,但是我不确定该如何处理。

I have pre-made the table but how to I go about adding a Users.email to the new select box, so far I have this in the index.html.erb. 我已经预先制作了表格,但是如何将Users.email添加到新的选择框中,到目前为止,我已经在index.html.erb中找到了。

 <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.time %></td>
        <td><%= post.body %></td>
        <td><%= post.user_id %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>

And this in my form.html.erb 这在我的form.html.erb中

%= form_for(post) do |f| %>
  <% if post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>

  <div class="field">
    <%= f.label :time %>
    <%= f.datetime_select :time %>
  </div>

  <div class="field">
    <%= f.label :body %>
    <%= f.text_area :body %>
  </div>

  <div class="field">
    <%= f.label :user_id %>
    <%= f.number_field :user_id %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

As you can see I have a user_id field but how would I go about linking that to the primary key of Users? 如您所见,我有一个user_id字段,但是如何将其链接到Users的主键? and then to do and email lookup? 然后做和电子邮件查找? Thanks. 谢谢。

Assuming you had association between Post and User model, 假设您在Post和User模型之间建立了关联,

If user login exists, then you can create post belonging to user like below, 如果存在用户登录名,则可以创建属于该用户的帖子,如下所示,

current_user.posts.create(post_params)

If user login not exists, then you can have the select box in post creation screen to choose the user and send the user_id of that user on submit. 如果不存在用户登录名,则可以在创建帖子后屏幕中使用选择框来选择用户,并在提交时发送该用户的user_id。

Saving user_id in post record is enough to associate post and user. 在帖子记录中保存user_id足以关联帖子和用户。

For example, 例如,

<%= f.collection_select :user_id, User.all, :id, :email %>

When viewing the posts, you can grab the user email like below, 查看帖子时,您可以像下面那样抓取用户电子邮件,

<td><%= post.user.email %></td>

Update 更新资料

To create association between Post and user model, run the following command. 要在Post和用户模型之间创建关联,请运行以下命令。

rails g migration add_user_to_posts user:references
rake db:migrate

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

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