因此,对文章和newsitems有评论的多态关系,每个评论也属于用户。到目前为止,我似乎已经完成了它的工作,并且在视图中,这适用于为每个发布的评论打印出user_id:
class SimpleGradebook():
def __init__(self, value = {}):
self._grades = value
def add_student(self,name):
self._grades[name] = []
book = SimpleGradebook()
book.add_student('test')
但显然我需要添加用户名/头像/等,而不是id。我如何访问这些值?
更新:关注mudasobwa的回答。
型号:
<% @comments.each do |comment| %>
<div>
<%= comment.updated_at.strftime("%b %d %Y, %H:%M") %></strong>
</div>
<div>
<%= comment.user_id %>
</div>
<div>
<%= comment.comment %>
</div>
<% end %>
在视图之后添加class User < ActiveRecord::Base
has_many :comments
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
…and…
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
会产生:
<%= comment.user.email %>
更新2:在视图中,它打印出它应该的内容:
undefined method `email' for nil:NilClass
答案 0 :(得分:0)
通过多态关联检索时,使用关联名称获取关联对象,例如:
comment.commentable
Rails将根据commentable_type
:
comment.commentable.class # => User