我有一个员工视图,其中列出了所有技能,这些技能都写在我的数据库的技能表中。对每一位员工来说,所有技能都会显示出来,就像想要的一样。Rails,解决这个n + 1的技巧?
员工和技能彼此之间有很多关联:通过关联。
class Employee < ApplicationRecord
has_many :employeeskillsets, foreign_key: "employee_id"
has_many :skills, through: :employeeskillsets
end
class Skill < ApplicationRecord
has_many :employeeskillsets, foreign_key: "skill_id"
has_many :employees, through: :employeeskillsets
end
class Employeeskillset < ApplicationRecord
belongs_to :employee, foreign_key: 'employee_id'
belongs_to :skill, foreign_key: 'skill_id'
end
所有这些技能都显示为按键,分别是切换启用/禁用该员工的特定技能(每点击直接插入/删除,没有多余的提交需要)。
<%= link_to apply_skill_employee_path(employee: @employee, skill_id: skill.id), method: :put, remote: :true do %>
<%= skill.name %></div><% end %>
但现在,我想要按钮显示颜色,当您加载页面。如果技能已经启用,buttoncolor应该是绿色的,否则是灰色的。这里开始我的问题: 我的应用程序检查每个技能与一个单独的选择语句。我为此使用以下代码:
<%= link_to apply_skill_employee_path(employee: @employee, skill_id: skill.id), method: :put, remote: :true do %>
<% if @employee.skills.exists?(skill.id) %>
<div class="button skill e-true"><%= skill.name %></div>
<% else %>
<div class="button skill"><%= skill.name %></div>
<% end %>
我已经尝试使用includes,但似乎存在?独立检查每项技能。
有没有人在这里有一个建议,我怎么能解决这个问题,通过使用一个单一的选择?
在此先感谢,我希望我已经提到了一切,什么是必要的。编辑1:我忘了提及,我通过部分渲染(如果知道这很重要)。 这里是employees_controller中当前使用的@employee var。
@employee = Employee.find_by(id: params[:id])
@max请详细说明,afaik作用域查询分贝.. –