【问题标题】:Trying to implement a grid view with a one-to-many association尝试实现具有一对多关联的网格视图
【发布时间】:2015-09-11 16:06:00
【问题描述】:

ImageCategory 有一个 one-to-many 关联:

# Category model:
has_many :images
# Image model:
has_one :category
# Images migration file:
t.references :category, index: true, foreign_key: true

我正在尝试使用wice_grid gem 实现网格视图。这有效,但一条线失败了。以下在索引视图中起作用:

g.column name: 'Category', attribute: 'category_id', auto_reload: true, html: {id: 'grid-cells'} do |image|
  image.category_id
end

但这会显示类别的编号/ID,而我希望它显示其名称。如果我尝试image.category 而不是image.category_id 则会出现错误:

PG::UndefinedColumn: ERROR:  column categories.image_id does not exist
LINE 1: SELECT  "categories".* FROM "categories" WHERE "categories"."image_id...

如何让它显示类别名称而不是类别的 ID?

控制器方法:

def index
  @images_grid = initialize_grid(Image,
  # include: :category  # Do I need this? Tried it with and without
  per_page: 40)
end

更新:在更正关联并在视图中使用下面的代码后,它可以工作了。此特定列的过滤器功能除外。如果我输入要过滤的文本,它会重新加载表格,但不应用过滤器(仍然显示所有记录)。

g.column name: 'Category', attribute: 'category_id', auto_reload: true, html: {id: 'grid-cells'} do |image|
  image.category.category unless image.category.nil?
end

【问题讨论】:

    标签: ruby-on-rails ruby postgresql ruby-on-rails-4 wice-grid


    【解决方案1】:

    在图像模型中你应该有belongs_to :category,而不是has_one。关联是 n-1,而不是 1-1。

    关于问题的第二部分 - 按类别名称过滤项目,我相信您需要使用自定义过滤器:

    g.column name: 'Category', attribute: 'images.category_id',
          custom_filter: Category.find(:all).map{|cat| [cat.id, cat.name]} do |image|
      image.category.name if image.category
    end
    

    【讨论】:

    • 谢谢,它有效。但是,对此特定列的过滤不起作用。如果我在过滤器字段中输入文本,它会重新加载表格但仍然包含所有记录。知道如何让它工作吗? (排序确实适用于列)
    • 我已经更新了一种处理过滤器的潜在方法。
    • 谢谢@stef。加载页面时会产生错误Couldn't find Category with 'id'=all。如果我将find(:all) 更改为.all,则会收到错误WiceGrid: Invalid attribute name images.category_id. An attribute name must not contain a table name!
    • 我在以下方面取得了成功:g.column name: 'Category', model: 'Category', attribute: 'name', auto_reload: true, html: {id: 'grid-cells'} do |image|image.category.name if image.categoryend。同时在控制器方法中包含include: :category
    【解决方案2】:

    has_many 的另一面是belongs_to。你需要图像模型说:

    belongs_to :category
    

    我用来记住哪个是“人和狗”的助记符:一个人has_many狗,一条狗belongs_to一个主人。哪个人的衣领上戴了“id_tag”?狗。所以 id 列在belongs_to 模型上。

    【讨论】:

      【解决方案3】:

      它有很多类别,所以你应该做类似的事情

      image.categories.find(:id)
      

      您需要获取类别的提供 ID,因为查询 image.categories 将返回图像所有类别的集合数组

      【讨论】:

      • 我相信我已经正确建模了它,因此图像具有 1 个类别...在图像模型中我有:has_one :category
      猜你喜欢
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多