Search code examples
ruby-on-railsformsruby-on-rails-3.1

Rails 3.1 - options_from_collection_for_select() pass in a value from a nested attribute as the option text


I have a select_tag like this:

<%= select_tag "User Groups", options_from_collection_for_select(@user_groups, "id", "name") %>

Here's my model

class Entity < ActiveRecord::Base
  has_many :user_groups
end

class UserGroup < ActiveRecord::Base
  belongs_to :entity 
end

The caveat is that there is no attribute called "name" for the UserGroup model, but there is one for the Entity model.

Ideally, I would like to pass in the values from the "name" attribute in the Entity model into the options_from_collection_for_select() method... something like this:

<%= select_tag "User Groups", options_from_collection_for_select(@user_groups, "id", @user_groups.each{|user_group| user_group.entity.name}) %>

But then I get something like this:

[#<UserGroup id: 1, entity_id: 3, created_at: "2012-03-15 02:36:28", updated_at: "2012-03-15 02:36:28">, #<UserGroup id: 2, entity_id: 4, created_at: "2012-03-15 02:42:36", updated_at: "2012-03-15 02:42:36">] is not a symbol

Is there a way I can use options_from_collection_for_select() and pass in a value from a nested attribute as the option text?


Solution

  • If you add this to your UserGroup model:

    def entity_name
      self.entity.name
    end
    

    You can then do

    <%= select_tag "User Groups", options_from_collection_for_select(@user_groups, "id", "entity_name") %>