如何在 Rails 4 中过滤索引的真值
How to filter index for true value in Rails 4
我正在尝试根据某个值是否为真来过滤数据库索引列表。这可能吗?在控制器中,我正在尝试这样做,这不会解决错误,但不会拉出我正在寻找的索引列表。
控制器:
def index
@people = Person.all
if params[:filter_by]
@people = Person.where(:position => params[:filter_by])
elsif
@people = Person.where(:ra_cs, params[:filter_by] == "true")
else
@people = Person.all
end
end
def person_params
params.require(:person).permit(
:fname, :lname, :user_name, :position, :title, :prefix, :focus1, :focus2, :focus3, :ra_cs, :ra_hn, :ra_mg, :ra_nb, :ra_ne)
end
数据库的条目是一个复选框,它在字段中输入值 1 或 0。
我不确定可能涉及哪些其他代码,如果我需要添加任何其他内容,请告诉我。
您需要重构您的代码:
def index
if params[:filter_by].present?
case params[:filter_by]
when 'ra_cs'
@people = Person.where(ra_cs: true)
when 'ra_aa'
@people = Person.where(ra_aa: true)
when 'ra_bb'
@people = Person.where(ra_bb: true)
else
@people = Person.where(position: params[:filter_by])
end
else
@people = Person.all
end
end
顺便说一句,elsif
需要一个条件。
另一种选择是使用动态 where
where 参数。
def index
@people = Person.all
@people = @people.where(params[:filter_by] => true) if params[:filter_by].present?
end
如果您不按每个属性筛选用户,您可以添加白名单。
def index
@people = Person.all
allowed = %w[ra_cs ra_aa ra_bb ...]
@people = @people.where(params[:filter_by] => true) if params[:filter_by].in?(allowed)
end
在第二个示例中,您不必检查是否存在,因为 nil
或 ""
将被返回,而 allowed
中没有。这意味着 if 语句无论如何都会计算为 false
。
我正在尝试根据某个值是否为真来过滤数据库索引列表。这可能吗?在控制器中,我正在尝试这样做,这不会解决错误,但不会拉出我正在寻找的索引列表。
控制器:
def index
@people = Person.all
if params[:filter_by]
@people = Person.where(:position => params[:filter_by])
elsif
@people = Person.where(:ra_cs, params[:filter_by] == "true")
else
@people = Person.all
end
end
def person_params
params.require(:person).permit(
:fname, :lname, :user_name, :position, :title, :prefix, :focus1, :focus2, :focus3, :ra_cs, :ra_hn, :ra_mg, :ra_nb, :ra_ne)
end
数据库的条目是一个复选框,它在字段中输入值 1 或 0。
我不确定可能涉及哪些其他代码,如果我需要添加任何其他内容,请告诉我。
您需要重构您的代码:
def index
if params[:filter_by].present?
case params[:filter_by]
when 'ra_cs'
@people = Person.where(ra_cs: true)
when 'ra_aa'
@people = Person.where(ra_aa: true)
when 'ra_bb'
@people = Person.where(ra_bb: true)
else
@people = Person.where(position: params[:filter_by])
end
else
@people = Person.all
end
end
顺便说一句,elsif
需要一个条件。
另一种选择是使用动态 where
where 参数。
def index
@people = Person.all
@people = @people.where(params[:filter_by] => true) if params[:filter_by].present?
end
如果您不按每个属性筛选用户,您可以添加白名单。
def index
@people = Person.all
allowed = %w[ra_cs ra_aa ra_bb ...]
@people = @people.where(params[:filter_by] => true) if params[:filter_by].in?(allowed)
end
在第二个示例中,您不必检查是否存在,因为 nil
或 ""
将被返回,而 allowed
中没有。这意味着 if 语句无论如何都会计算为 false
。