Rails:基于多个参数进行过滤? [英] Rails: Filter based on multiple params?
问题描述
我有一个简单的应用程序,用户可以根据类别,学科和目标群体基于三种不同的参数进行过滤。所有参数都是可选的。到目前为止,它仍然有效,但是下面的控制器有点肿,我还认为这三个if语句有点混乱。
I have a simple app and the user can filter based on three different params by category, by discipline and by target group. All params are optional. So far it works, but the controller below is a bit bloated and I also think the three if statements are a bit messy.
有没有更清洁的方法?
Is there a cleaner way to do this?
def index
@listings = Listing.includes(:categorizations, :listing_disciplines, :listing_targets).page(params[:page])
if params[:category_id].present? && params[:category_id] != ""
@category_id = Category.find_by(id: params[:category_id])
@listings = @category_id.listings
end
if params[:discipline_id].present? && params[:discipline_id] != ""
@discipline_id = Discipline.find_by(id: params[:discipline_id])
@listings = @discipline_id.listings
end
if params[:target_id].present? && params[:target_id] != ""
@target_id = Target.find_by(id: params[:target_id])
@listings = @target_id.listings
end
if params.blank?
@listings
end
这是我的列表模型:
class Listing < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
has_many :categories, through: :categorizations
has_many :listing_disciplines, dependent: :destroy
has_many :disciplines, through: :listing_disciplines
has_many :listing_targets, dependent: :destroy
has_many :targets, through: :listing_targets
has_attached_file :image, styles: { :medium => "200x200#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :title, presence: true, uniqueness: true
paginates_per 15
end
推荐答案
我不确定您的代码是否有效,因为您正在重置每个 param
的列表。我假设您希望能够同时按所有三个条件进行过滤。较干净的方法是:
I'm not confident that your code even works, because you are resetting listings with each param
. I assume you want to be able to filter by all three at once. A cleaner way would be:
def index
@listings = Listing.joins(:categorizations, :listing_disciplines, :listing_targets)
@listings = @listings.where("categorizations.category_id = ?", params[:category_id]) if params[:category_id].present? && params[:category_id] != ""
@listings = @listings.where("listings_disciplines.discipline_id = ?", params[:discipline_id]) if params[:discipline_id].present? && params[:discipline_id] != ""
@listings = @listings.where("listing_targets.target_id = ?", params[:target_id]) if params[:target_id].present? && params[:target_id] != ""
@listings = @listings.page(params[:page])
end
这将使所有过滤器累积。
This will make all filters cumulative.
这篇关于Rails:基于多个参数进行过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!