简体   繁体   中英

query to fetch data from has_many through association

class Employee < ActiveRecord::Base
  has_many :sim_employees, dependent: :destroy
  has_many :sims, through: :sim_employees
end

in my sim_employees table I have employee_id sim_d and 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

So now my requirement is

employees/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%>

Now 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. Thanks in advance.

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

Write this method in employee.rb

In view

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

 <%= employee.name%>
 <%= employee.of_call_type %>
<%end%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM