【发布时间】:2013-09-13 23:14:41
【问题描述】:
在我的 Rails 3.2 应用程序中,我有 User、Comment 和 Article 模型。在一个视图中,我试图显示按文章日期排序的所有用户 cmets(cmets 属于文章)。问题是,在我看来,当我尝试检索评论 id 时,我得到了文章 id。
***Models***
# user.rb
has_many :comments
# comment.rb
belongs_to :user
belongs_to :article
scope :by_article_date,
select("*, articles.date as article_date").
joins(:article).
order("article_date DESC")
# article.rb
has_many :comments
# users_controller
def comments
@user = current_user
@comments = @user.comments.by_article_date
end
# comments.html.erb
<% @comments.each do |comment| %>
<%= comment.id %> # shows the article id, but should be comment.id
<%= comment.article.id %> # shows article id correctly
<% end %>
有人可以帮我弄清楚发生了什么吗?
【问题讨论】:
-
你能通过调用
@comments.first.class来调试你的实例变量@comments吗?然后,您将能够查看是否获得了 cmets 或文章的集合。 -
当我放 它返回
Comment -
嗯,情节变厚了。您能否准确告诉我们您是如何发现它返回的是文章 ID 而不是评论 ID?
-
我首先发现它是因为我在视图中有 并且它指向一个不存在的记录,所以我意识到它是使用文章 ID。如果我在控制器中设置
@comments = @user.comments,则视图有效,但如果我这样做,它不会按 Article.date 排序 -
在你的范围内试试这个:
scope :by_article_date, -> { joins(:article).order("articles.article_date DESC") }
标签: ruby-on-rails ruby-on-rails-3.2 rails-activerecord