使用模型后的最后使用不起作用

时间:2013-01-27 17:27:49

标签: mysql database ruby-on-rails-3

我陷入困境(对Rails来说仍然很新),并且无法弄清楚它为什么不起作用:

我有:

    class Message < ActiveRecord::Base
     attr_accessible :updated_at
     has_many :categories_messages
     has_many :categories, through: :categories_messages
    end

    class CategoriesMessage < ActiveRecord::Base
     attr_accessible :category_id, :message_id
     belongs_to :category
     belongs_to :message
    end

    class Category < ActiveRecord::Base
     attr_accessible :name
     has_many :categories_messages
     has_many :message, through: :categories_messages
    end

    @messagesPer = Category.all.includes(:messages).group('categories.id').order("COUNT(messages.id) DESC")


    <% @messagesPer.each_with_index do |message,  i| %>
         <tr>
            <td><%= i+1 %></td> 
            <td><%= message.name %></td>
            <% if message.categories_messages.exists? %>
                <td><%= message.messages.last.updated_at.to_s.to_date %></td>
                <td><%= message.messages.first.updated_at.to_s.to_date %></td>
                <td><%= message.messages.count %></td>
            <% else %>
                <td>0</td>
                <td>0</td>
            <% end %>
        </tr>
    <% end %>

所以我想要它显示: 类别的名称,创建最后一条消息的日期,创建日期第一条消息以及该类别中的所有消息。

ALl工作正常,除了它只显示创建第一条消息的日期,但从不显示最后一条消息(仍显示最后一条消息的第一个日期)。 我做错了什么?

更新:

如果我把

     @messagesPer = Category.all.includes(:messages).group('categories.id')

它确实显示了最后一条和第一条消息的正确日期,但只要我添加订单就会中断...

1 个答案:

答案 0 :(得分:0)

在向查询添加order子句后,我可能会帮助您包含错误信息。

但是,我可以在代码中发现一些奇怪的东西。 CategoriesMessage模型似乎只是为了满足类别可以包含许多消息的条件,反之亦然。您不需要这种多对多关系的模型,Rails会自动为您处理。

你的模特应该是这样的:

class Message < ActiveRecord::Base
 attr_accessible :updated_at
 has_and_belongs_to_many :categories
end

class Category < ActiveRecord::Base
 attr_accessible :name
 has_and_belongs_to_many :messages
end

在您的数据库中,您有以下表:messagescategories, categories_messages , where the last one is the join table which only contains columns for a message_id and a category_id`。

然后您可以在代码中执行以下操作:

category.messages.each { |message| puts message.updated_at }

有关详情,请参阅this Ruby on Rails tutorial article。如果这不适合您,请发布您得到的确切错误。