【问题标题】:Custom filter for grid view not working (two associated models)网格视图的自定义过滤器不起作用(两个关联模型)
【发布时间】:2015-05-30 04:35:18
【问题描述】:

我正在使用wice_grid 并有两个关联的表:组织和用户(具有 1:many 关系)。对于所有用户的网格视图,我想包含一个列,该列说明用户所属的组织的名称(组织模型中的变量)。为此,我定义了一个自定义过滤器,gem 为其提供了说明here

我为网格视图定义了以下列:

g.column name: 'Organization', filter_type: :string, attribute: 'users.organization_id', 
         custom_filter: Organization.all.map{|pr| [pr.id, pr.organizationname]} do |user|
  link_to(user.organization.organizationname, organization_path(user.organization))
end

由此产生的错误信息(参考第一行):

WiceGrid: Invalid attribute name users.organization_id. An attribute name must not contain a table name!

但我确实觉得我完全掌握了说明中的示例。知道我做错了什么吗?


更新:如果我将第一行更改为:

g.column name: 'Organization', filter_type: :string, attribute: 'organization_id', 

页面呈现没有错误。但是,此列的过滤器是一个下拉框,而不是字符串的搜索字段(将其更改为 filter_type: :string 无效)。另外,如果我尝试对列进行排序,页面会出现以下错误。任何想法如何定义列/自定义过滤器?

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "Gutmann-Stroman 95"
LINE 1: ...OM "users" WHERE (( users.organization_id = 'Gutmann-S...
                                                             ^
: SELECT COUNT(*) FROM "users" WHERE (( users.organization_id = 'Gutmann-Stroman 95'))

user表中的organization_id保存了用户所属组织的id号。 “Gutmann-Stroman 95”是与 id 关联的 organizationname。我将friendly_id 用于友好的url,它在url 中转换名称中的id;也许这与它有关?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 gridview associations


    【解决方案1】:

    但我确实觉得我完全掌握了说明中的示例。

    错了。该示例指定了model: 'Project',而您没有。该示例使用连接表的name,而您没有。您的代码尽可能远离示例。另外,您在文档中的哪个位置看到filter_type: :string

    你应该有类似的东西

    g.column name: 'Organization', model: 'Organization', attribute: 'organizationname' do |user|
      link_to(
        user.organization.organizationname, 
        organization_path(user.organization)
      )
    end
    

    initialize_grid 中,您需要正确包含您的关联:

    yourgrid = initialize_grid(User,
      include:  [:organization]
    )
    

    在这里您可以看到一个工作示例:http://wicegrid.herokuapp.com/joining_tables

    【讨论】:

    • 谢谢,我提到的例子略低于你提到的例子。以`g.column name: 'Project Name', attribute: 'tasks.project_id',`开头的那个。因为我明白上面的例子“风格不好,可能会失败”。无论如何,我现在已经按照你的建议实现了,这样确实更有意义。它确实对我的网格有用,就像我原来的帖子一样!太好了!
    • 无法让它为另一个关联的网格工作:奖品has many 组织。在奖品网格中,我想要一列:prize.organizations.count.to_s。我将include: [:organization] 包含在initialize_grid 中。 g.column name: 'Count', model: 'Organization', attribute: 'prize_id' do |prize|prize.organizations.count.to_send。错误:Association named 'organization' was not found on Prize。问题是该奖项没有组织专栏;该组织的表格有一列包含与该组织相关联的奖品(如果有)的 ID。
    • 我的错误是 include: [:organization] 应该是 include: [:organizations]
    猜你喜欢
    • 2014-12-23
    • 2015-09-24
    • 2021-07-31
    • 2012-08-19
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2015-06-15
    相关资源
    最近更新 更多