-->

洗劫:使用的,而不是出生日期年龄(Ransack: using age instead of dat

2019-08-04 14:47发布

我想用洗劫建立一个先进的搜索功能与网页Users 。 我有一个小方法,从诞生之日起计算年龄:

def age(dob)
  now = Time.now.utc.to_date
  now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
end

该工程正常显示( as in age(@user.date_of_birth)

但是,当使用search_form_for我不能这样做:

<%= search_form_for @search, url: search_users_path, method: :post do |f| %>
    <div class="field">
        <%= f.label :date_of_birth_gteq, "Age between" %>
        <%= f.text_field :date_of_birth_gteq %>
        <%= f.label :date_of_birth_gteq, "and" %>
        <%= f.text_field :date_of_birth_lteq %>
    </div>
<div class="actions"><%= f.submit "Search" %></div>
 <% end %>

我的问题是:我该如何使用年龄在我的搜索,而不是出生日期?

Answer 1:

添加范围如下图所示找到了特定年龄的日期。

scope :age_between, lambda{|from_age, to_age|
  if from_age.present? and to_age.present?
    where( :date_of_birth =>  (Date.today - to_age.to_i.year)..(Date.today - from_age.to_i.year) )
  end
}

对于ransacke语法:

ransacker :age, :formatter => proc {|v| Date.today - v.to_i.year} do |parent|
  parent.table[:date_of_birth]
end   

鉴于

<%= f.text_field :age_gteq %>


Answer 2:

我不知道ransacker亲自尝试使用ransacker但找不到,可以检查传入的谓词的任何事情。因此,我认为这是更好地使用范围来做到这一点。

def self.age_lteq(age)
  start_birth_year = Date.today.year - age
  where('date_of_birth >= ?', Date.new(start_birth_year))
end

def self.age_gteq(age)
  birth_year = Date.today.year - age
  end_of_birth_year = Date.new(birth_year + 1) - 1
  where('date_of_birth <= ?', end_of_birth_year)
end

private

def self.ransackable_scopes(auth_object = nil)
  %i(age_lteq age_gteq)
end

# In views just do the following (ransack default grouping queries is by AND)
# https://github.com/activerecord-hackery/ransack#grouping-queries-by-or-instead-of-and
<%= f.input :age_lteq %>
<%= f.input :age_gteq %>

@siddick答案是凉的,但逻辑lteq行为像gtgteq行为像lt 。 我自己是最近开始了Ruby和Rails。 所以,不要告诉我,如果我做错了什么。 :) 谢谢!



Answer 3:

在@siddick答案只是一个更新(这完美的作品)。 现在,你需要给洗劫提供白名单范围。 在从@siddick你需要做的这个答案的情况下:

def self.ransackable_scopes(auth_object = nil)
  %i(age_between)
end

欲了解更多信息请参阅该文档- https://github.com/activerecord-hackery/ransack#using-scopesclass-methods



文章来源: Ransack: using age instead of date of birth