RUBY ON RAILS查询关联关系

时间:2017-12-19 11:49:38

标签: ruby-on-rails associations

class Persson
   has_many : accounts
   has_many : computers, through : :accounts
end

class Account
   belongs_to : person
   belongs_to : computer
   scope :administrtor, -> { where(role : 'administrator') }
end

class Computer
  has_many :accounts
  has_many :person, though: :accounts
end

1.找到此人(身份证号码39)为管理员的所有计算机。

2.找到所有在多台计算机上担任管理员的人。

3.找到只有一个管理员的所有计算机。

1 个答案:

答案 0 :(得分:1)

嘿,请查看关联rails文档doc 假设您正在使用PostgreSQL来解决您的问题

1

public void SortingList(List<string> list,string keyword)
        {
            IEnumerable<string> filterLst = list.Where(s => s.StartsWith(keyword[0].ToString(), StringComparison.OrdinalIgnoreCase));

            var result = filterLst.OrderBy(s => !s.StartsWith(keyword, StringComparison.OrdinalIgnoreCase))
                 .ThenBy(s => !s.ToLower().Contains(keyword));

            foreach (string s in result)
            {
                Console.WriteLine(s);
            }

        }

2

Person.includes(:accounts).find(1).computers.where("accounts.role =?", 'administrator')

3

Person.where(id: Account.administrtor.group("accounts.person_id").having("count(accounts.person_id) > 1").pluck("accounts.person_id"))