【问题标题】:query to fetch data from has_many through association查询通过关联从 has_many 中获取数据
【发布时间】:2015-09-18 10:44:14
【问题描述】:
class Employee < ActiveRecord::Base
  has_many :sim_employees, dependent: :destroy
  has_many :sims, through: :sim_employees
end

在我的 sim_employees 表中,我有 employee_id sim_d 和 is_local::boolean。

id employee_id sim_d  is_local
1    1           2      1
2    1           3      0
3    1           5      0
4    2           1      0
5    2           8      0

所以现在我的要求是

员工/index.html.erb

<%@employees.each do |employee|%>

 <%=employee.name%>
 # here I need a query if employee.id  is_local is 1 for all employee than it will show local. If it is a combination of both 1 and 0 than it will show local/std if its 0 then it will show std. Please let me know how I will fetch this data from sim_employees table here.
<%end%>

现在我需要查询所有员工的employee.id is_local 是否为1,而不是显示本地。如果它是 1 和 0 的组合,那么它将显示 local/std,如果它是 0,那么它将显示 std。请让我知道如何从 sim_employees 表中获取这些数据。提前致谢。

【问题讨论】:

    标签: mysql ruby-on-rails has-many-through


    【解决方案1】:
    def of_call_type
        call_types = self.sim_employees.map(&:is_local)
        if call_types.include?(true) and call_types.include?(false)
            "Local/STD"
        elsif call_types.include?(true)
            "Local"
        else
            "STD"
        end
    end
    

    把这个方法写在employee.rb中

    在视图中

    <%@employees.each do |employee|%>
    
     <%= employee.name%>
     <%= employee.of_call_type %>
    <%end%>
    

    【讨论】:

    • 请指导我如何编写此查询self.sim_employees.each do |se| p 'aaaa' p se.sim.is_active end so 我需要在查询中检查se.sim.is_active 是真是假我将如何做到这一点
    • 没有得到你的问题..你能解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2013-04-22
    • 2015-12-19
    • 1970-01-01
    相关资源
    最近更新 更多