小编hac*_*att的帖子

Rails4 动态选择下拉菜单

我正在尝试使用 form_tag 在搜索表单中设置一些动态下拉选择菜单。我想要的是与Railcasts #88 中的示例类似的功能

楷模:

class Count < ActiveRecord::Base
  belongs_to :host
end

class Host < ActiveRecord::Base
  belongs_to :site
  has_many   :counts
end

class Site < ActiveRecord::Base
  belongs_to :state
  has_many   :hosts
end

class State < ActiveRecord::Base
  has_many :sites
end
Run Code Online (Sandbox Code Playgroud)

看法:

<%= form_tag(counts_path, :method => "get", id: "search-form") do %>
  <%= select_tag "state_id", options_from_collection_for_select(State.all.order(:name), :id, :name) %>
  <%= select_tag "site_id", options_from_collection_for_select(Site.all.order(:name), :id, :name) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

状态 has_many Sites which has_many Hosts 有许多计数。或者相反,计数属于状态的属于主机的属于状态的站点

因此,我想从“状态”下拉列表中选择一个状态,然后根据站点通过主机关联的状态“分组”站点。

我一直在努力解决这个嵌套关联,似乎无法弄清楚如何构建 grouped_collection_select。

我知道我忽略了一些明显的东西!可以肯定使用一些指针...

collections ruby-on-rails model-associations

3
推荐指数
1
解决办法
2238
查看次数