0

Using the solution of my previous question: Rails: Create a new entry in a model that belongs_to two other models, I would like to display all the opinions collected by a store.

To recap, I have a Store that has_many Products that have_many Opinions (see the previous link to have more details about models code)

In order to get all the opinions collected by a store, I use the following code in the OpinionsController:

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

And then, in the show.html.haml view, I use this code to display the opinions:

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

What can I do to order opinions by opinion.created_at, no matter what the parent product is?

More generally, how to order using a parameter from the second generation child association?

Thanks in advance.

Community
  • 1
  • 1
Hassen
  • 6,966
  • 13
  • 45
  • 65

1 Answers1

1

I don't see why you have to use the second generation child association, if Opinion has a store_id.

Couldn't you just do it this way?:

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

And then in your view:

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

Alternatively, with only @store defined in the controller (as you have it), you could do this in the view:

%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
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • Thanks shioyama. I choosed the second solution because I didn't want to get Opinions directly, but the Store. – Hassen Aug 20 '12 at 11:40