【问题标题】:Rails - grouped_collection_selectRails - grouped_collection_select
【发布时间】:2012-06-04 18:19:39
【问题描述】:

我正在尝试通过以下方式获取 grouped_collection_select

class User
  has_many :pages, :through => pages_users
end

class Page
  has_many :users, :through => pages_users
  # name - String
  # type - String
end

class PagesUser < ActiveRecord::Base
  belongs_to :page 
  belongs_to :user
end

我希望下拉菜单按类型分组,下面有名称。我在城市/国家/大陆看到的示例并没有我想要的那么有用。这样做的最佳方法是什么?我想我想要...

<%= grouped_collection_select(:user, :page_id, user.pages, :type, :name, ) %>

但这显然是不正确的。

有什么想法吗?

已编辑以通过 pages_users 表显示实际关系。

【问题讨论】:

  • 应该是 has_many 用户(现已修复)。

标签: ruby-on-rails ruby forms


【解决方案1】:

这就是我最终得到的结果......

<%= select_tag 'page_id', grouped_options_for_select(Page.for_select) %>

Page.for_select 的样子...

def for_select
  {
    'Type 1'   => type1.map { |p| [p.name, p.id] },
    'Type 2' => type2.map { |p| [p.name, p.id] }
  }
end

希望这对其他人有所帮助。

【讨论】:

  • 我认为将for_select 方法放入模型中并不是一个好主意。应该是辅助方法
【解决方案2】:

将其视为简单的一对一关系,

class User
  has_many :pages
end

class Page
  # name - String
  # type - String
end

<%= grouped_collection_select(:user, :page_id, user.pages.map(&:type), :pages_by_type, :name, :id, :name ) %>

为此,您需要一种机制来查找给定类型的所有页面。

【讨论】:

  • 如果是many_to_many关系,则改为has_and_belongs_to_many,如图。你有第三个 users_pages 关系表吗?
  • 是的,还有一个 pages_users 表。显然,我不应该试图简化这么多。我想我想知道为什么页面与用户的关系很重要。我真的只对用户拥有的页面感兴趣。我错过了什么吗?另外,为什么 collection_select 而不是 grouped_selection_select?
  • 查看collection_select,它似乎没有达到我想要的效果。我想要页面类型的 optgroup 标签,然后是下面的页面名称。
  • pages_by_type 是 Pages 上的一种方法吗?是传入的类型,然后你取回该类型的所有页面吗?另外,在地图中,我认为它应该是 user.pages.map(&:type) (括号而不是花括号)。为了澄清起见,最后的 :id 用于页面,而 :name 也用于页面?
  • 更改了地图。最终 ID 和名称在页面上。我已经在三个表而不是两个表中使用了这种语法,所以需要测试 pages_by_type 部分。
猜你喜欢
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多