给定示例中的collection_select

时间:2014-03-02 22:08:36

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

application_controller.rb

  def find_user_favorites
    @user_fav_categories = current_user.favorites.map(&:category)
  end

这就是我目前列出所有类别名称的方式:

    <% @user_fav_categories.each do |fav| %>
      <%= fav.name %>
    <% end %>

如何使用collection_select创建列表?

2 个答案:

答案 0 :(得分:0)

我想问题是你将使用什么样的集合,试试这个

collection_select(
  Category,
  :name,
  Category.joins(:favorites).where('favorites.user_id: current_user.id),
  :id,
  :name
)

答案 1 :(得分:0)

这应该有效

<%=collection_select(Category, :name, @user_fav_categories, :id, :name)%>
相关问题