0

使用我上一个问题的解决方案:Rails: Create a new entry in a model that belongs_to two other models,我想显示商店收集的所有意见。

回顾一下,我有一个商店 has_many Products that have_many Opinions(请参阅上一个链接以获取有关模型代码的更多详细信息)

为了获取商店收集的所有意见,我在 OpinionsController 中使用以下代码:

# Show a specific store opinions.
def show
    @store = Store.find_by_id params[:store_id]
end

然后,在 show.html.haml 视图中,我使用这段代码来显示意见:

%table
    - @store.opinions.each do |opinion|
        %tr
            %td= opinion.id
            %td= opinion.content
            %td= opinion.product.name
            %td= opinion.created_at

无论父产品是什么,我可以做什么来通过 opinion.created_at 订购意见?

更一般地,如何使用来自第二代子关联的参数进行排序?

提前致谢。

4

1 回答 1

1

如果 Opinion 有一个store_id.

你就不能这样吗?:

# Show a specific store opinions.
def show
  @opinions = Opinion.order(:created_at).find_all_by_store_id params[:store_id]
end

然后在你看来:

%table
  - @opinions.each do |opinion|
    %tr
      %td= opinion.id
      %td= opinion.content
      %td= opinion.product.name
      %td= opinion.created_at

或者,仅@store在控制器中定义(如您所愿),您可以在视图中执行此操作:

%table
  - @store.opinions.scoped.order(:created_at).each do |opinion|
    %tr
      %td= opinion.id
      %td= opinion.content
      %td= opinion.product.name
      %td= opinion.created_at
于 2012-08-18T10:08:12.483 回答