使用 Ransack gem 按年龄过滤的未定义方法错误 [英] Undefined method error for filtering by age using Ransack gem

查看:37
本文介绍了使用 Ransack gem 按年龄过滤的未定义方法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ransack 按年龄过滤结果,但是 ransack 给了我一个未定义的方法错误.我的数据库中有用户 DOB,在我的用户模型中,我有一个计算用户年龄的年龄方法.它工作得很好,我可以这样称呼用户年龄:

I am trying to filter results by age using ransack, but ransack is giving me an undefined method error. I have the Users DOB in my database and in my users model I have an age method that calculates the age of the user. It works perfectly fine and I am able to call the users age like this:

@user = User.find(1)
@user.age

现在进行洗劫,我的控制器中有以下内容:

Now for ransack I have the following in my controller:

  def index
   @search = User.search(params[:q])
   @users = @search.result
  end

在我看来,我有:

<%= search_form_for @search do |f| %>
    <%= f.label :age_gteq, "Ages:" %> <%= f.text_field :age_gteq %>
    <%= f.label :age_lteq, "to" %> <%= f.text_field :age_lteq %>
    <%=f.submit "Filter", class: "button" %>
<% end %>

这是我得到的错误:

undefined method `age_gteq' for Ransack::Search<class: User, base: Grouping <combinator: and>>:Ransack::Search

我确信对于 age_lteq

推荐答案

据我所知它不起作用,因为目前 Ransack 仅适用于数据库列.最后 Ransack 只是一个复杂的 SQL 查询生成器.

As far as I know it doesn't work, because currently Ransack only works with database columns. In the end Ransack is just a sophisticated SQL query generator.

想想这个例子:

User.where('age >= ?', 30)

SQL 查询是什么样的?

What would a SQL query look like?

SELECT * FROM user WHERE age >= 30

即使 Ransack 会在正常的非数据库属性上通过这些条件,SQL 仍然是错误的.(因为没有age栏)

Even if Ransack would pipe through such conditions on normal non-database attributes, the SQL would still be wrong. (Since there is no age column)

一种解决方案是在表单中使用原始的出生日期列,并使用一些 Javascript 来允许用户输入年龄数字而不是日期.例如通过监听 onsubmit 事件并修改 input 的内容.

One solution would be to use the original date-of-birth column in your form and use some Javascript to allow the user to enter age numbers instead of dates. For example by listening to the onsubmit event and modify the input's content.

2014-01-08 更新:

还有另一种可能性来完成这项工作.将此添加到您的 User 模型:

There is another possibility to make this work. Add this to your User model:

ransacker :age do
  Arel::Nodes::SqlLiteral.new(
     'DATE_PART('year', AGE(NOW(), date_of_birth_column))') 
  # Beware: PostgreSQL specific SQL!
end

ransacker"需要返回一个 Arel 节点,该节点稍后将附加到 Ransack 生成的 Arel 节点上.

A "ransacker" needs to return an Arel node which later will be attached to the Arel nodes generated by Ransack.

这允许您像使用常规数据库列一样使用 age_eq 和所有其他 Ransack 谓词.

This allows you to use age_eq and all the other Ransack predicates just as it were a regular database column.

这篇关于使用 Ransack gem 按年龄过滤的未定义方法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆