我正在尝试创建一个可从中选择用户的下拉菜单。我还希望在名称旁边显示分配给他们的项目数量
class User < ActiveRecord::Base
attr_accessible :email, :username, :password, :password_confirmation, :remember_me, :first_name, :last_name
belongs_to :department
has_many :project_assignments
class ProjectAssignment < ActiveRecord::Base
attr_accessible :user_id, :project_id, :active, :notes
belongs_to :user, counter_cache: :projects_count
belongs_to :project
end
class Project < ActiveRecord::Base
attr_accessible :program_id, :title, :status, :topic_number, :award_number, :task_data_attributes, :user_ids, :technical_poc_id, :contacts_attributes, :project_fields_attributes, :division_id, :company_name
attr_accessor :old_project_id
belongs_to :program
belongs_to :division
belongs_to :company
has_many :users, through: :project_assignments
<div class="col-md-12">
<p>New Assignment</p>
<%= form_for @project.project_assignments.new, url: program_project_assignments_path(@program, @project), html: { id: 'staff-form' } do |f| %>
<%= f.select :user_id, options_from_collection_for_select(User.all, :id, :full_name), {}, class: 'form-control input-sm', placeholder: 'User' %>
<%= hidden_field_tag "project_id",nil,:value => @project.id %>
<%= f.submit 'Assign', class: 'btn-gray' %>
<% end %>
</div>
以上所有代码只是各自文件的摘录。上面的html用于填充带有名称的下拉列表,但显然没有代码试图添加已分配项目的数量
答案 0 :(得分:0)
<%= f.select :user_id, options_for_select(User.all.collect{|u|["#{u.full_name} #{u.project_assignments.count}", u.id]}), {}, class: 'form-control input-sm', placeholder: 'User' %>
在控制器中加载用户和急切加载项目分配将是高效的
@users = User.includes(:project_assignment).all