人。我有两个简单的模型:
class Restaurant < ApplicationRecord
has_many :reviews
end
和
class Review < ApplicationRecord
belongs_to :restaurant
end
任务是在餐馆或餐馆找到后显示所有评论
像这样的东西
class ReviewsController < ApplicationController
def index
@search = Restaurant.search(params[:q])
@reviews = @search.result.reviews
end
端
但是这段代码不知道评论消息,因为它不是AR :: Relation
一个非常糟糕的解决方案看起来像
def index
@search = Restaurant.ransack(params[:q])
@reviews = @search.result.each_with_object([]) do |rest, arr|
arr << rest.reviews
end
端
但观点非常糟糕。有一种简单的方式来获得评论吗? 感谢
答案 0 :(得分:1)
这个怎么样
def index
@search = Restaurant.ransack(params[:q])
@reviews = Review.where(restaurant_id: @search.result.pluck(:id))
end
答案 1 :(得分:1)
Ransack的文档说明你可以预先加载结果。 See here
更新后的代码如下所示:
class RestaurantController < ApplicationController
def index
@q = Restaurant.ransack(params[:q])
@restaurants = @q.result.includes(:reviews)
end
end
最后,这是一个有趣的相关问题:https://stackoverflow.com/a/39271500/648695