我正在尝试为博客上的帖子打印所有评论及其相关用户。评论传入 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/