0

guys. I have two simple models:

class Restaurant < ApplicationRecord
  has_many :reviews

end

and

class Review < ApplicationRecord
  belongs_to :restaurant

end

Task is to show all reviews after restaurant or restaurants found

Something like that

class ReviewsController < ApplicationController
  def index
  @search = Restaurant.search(params[:q])
  @reviews = @search.result.reviews
end

end

But this code does not know reviews message cause it`s not an AR::Relation

A very bad solution looks like

def index
  @search = Restaurant.ransack(params[:q])
  @reviews = @search.result.each_with_object([]) do |rest, arr|
     arr << rest.reviews
  end

end

But views are very awful. Is there a simple way to get reviews? Thanks

zOs0
  • 315
  • 2
  • 9

2 Answers2

1

How about this

def index
  @search  = Restaurant.ransack(params[:q])
  @reviews = Review.where(restaurant_id: @search.result.pluck(:id))
end
krishnar
  • 2,537
  • 9
  • 23
  • It is very funny. I click submit button on reviews_path and it redirects me to restaurants_path and shows restaurants found – zOs0 Sep 24 '17 at 17:44
1

Ransack's docs state you can preload off of the result. See here.

Updated code would look something like this:

class RestaurantController < ApplicationController
  def index
    @q = Restaurant.ransack(params[:q])
    @restaurants = @q.result.includes(:reviews)
  end
end

Lastly, here's an interesting related question: https://stackoverflow.com/a/39271500/648695

Mario Zigliotto
  • 8,315
  • 7
  • 52
  • 71