ruby-on-rails - rails : ActiveRecord Association returns a nil relationship

标签 ruby-on-rails ruby

我正在尝试为博客上的帖子打印所有评论及其相关用户。评论传入 View ,可以访问到他们的users_id和posts_id,但是我访问不到他们的用户; comment.user 返回 nil。

型号:

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

迁移:

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :text
      t.references :users
      t.references :posts
      t.timestamps
    end
  end
end

在 Controller 中:

@post = Post.find(params[:id])
@comments = Comment.where(posts_id: params[:id]).order(:created_at)

在 View 中:

<% @comments.each do |c| %>
  <% c.user.nil? %>
    <p><%=c.text%></p>
    <p><%=c.users_id%></p>
    <p><%=c.posts_id%></p>
  <% else %>
    <p><%=c.text%></p>
    <p><%=c.user.name%></p> #Here is where things would break if I didn't check "c.user.nil?"
  <% end %>
<% end %>

评论的文本和 ID 按预期打印,但用户仍被视为 nil。有谁知道如何从 View 中的评论模型中访问用户?

最佳答案

我认为问题在于您数据库中外键列的名称。在声明 post 关联的同时显式声明外键(您可以这样做)时,它将在模型上查找 post_id。因此,您应该将数据库中的列更改为 post_id,或者将关联方法调用更改为:

belongs_to :post, foreign_key: :posts_id

关于ruby-on-rails - rails : ActiveRecord Association returns a nil relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513590/

相关文章:

ruby-on-rails - 通过设计登录/注册后保留表单数据

ruby 目录函数

ruby-on-rails - 在运行时删除验证

jquery - 如何在 Rails 中重新排序表格数据,以便最新数据显示在顶部?

ruby-on-rails - 使用 Barby gem 打印 - 条码图像模糊

ruby-on-rails - 使用 STI 为 rails 中的子模型指定唯一属性

ruby-on-rails - Ruby 数组范围

sql - ActiveRecord:find_by_sql 并包括

javascript - 如何使用 onblur 在 javascript 中隐藏一个 div - rails

ruby - 使用 unpack 编写带有十六进制字符的字节数组?