0

在我的 Rails 3.2 应用程序中,我有UserCommentArticle模型。在一个视图中,我试图显示按文章日期排序的所有用户评论(评论属于文章)。问题是,在我看来,当我尝试检索评论 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 %>

有人可以帮我弄清楚发生了什么吗?

4

1 回答 1

0

在你的范围内试试这个:

scope :by_article_date, -> { joins(:article).order("articles.date DESC") }
于 2013-09-14T00:08:11.383 回答