Rails - grouped_collection_select

时间:2012-06-04 18:19:40

标签: ruby-on-rails ruby forms

我正在尝试使用以下

获取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表显示实际关系。

2 个答案:

答案 0 :(得分:5)

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

<%= 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

希望这有助于其他人。

答案 1 :(得分: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 ) %>

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