代码之家  ›  专栏  ›  技术社区  ›  Viren

ActiveRecord混合条件+更好的编写方法

  •  1
  • Viren  · 技术社区  · 14 年前

    有更好的方法写这个吗

    我以前的情况看起来很干净,很容易理解 喜欢

    Account.first.websites.last.users.find(:all,
                 :conditions => {:country => "XYZ",:status => "Single",:admin => nil)
    

    现在最大的问题是用户 管理员=假 没有被拾起。

    也就是说,我希望来自特定国家的所有用户都具有 “single”和admin是“nil”(数据库中为空)或“false”。

    我设法获得了所需的代码,但似乎对清晰不满意 其中。

    Account.first.websites.last.users.find(:all,
        :conditions => ["country = ? AND status = ? AND admin IS NULL OR 
           admin = ?","XYZ","Single","false"])
    

    任何帮助都将不胜感激。

    谢谢

    2 回复  |  直到 14 年前
        1
  •  1
  •   klew    14 年前

    我将在模型中添加一些范围:

    scope :not_admin, where("admin is null or admin = ?", false)
    scope :single, where("status = ?", "single")
    scope :from_country, lambda {|country| where("country = ?", country}
    

    然后在控制器中使用它:

    Account.first.websites.last.users.from_country("XYZ").single.not_admin
    

    您还可以使用自动生成的作用域:

    Account.first.websites.last.users.scoped_by_country("XYZ").scoped_by_status("single").not_admin
    

    我只离开这里 not_admin 范围。

        2
  •  1
  •   Codebeef    14 年前

    尝试以下操作:

    Account.first.websites.last.users.all(:conditions => ["country = ? AND status = ? AND admin != true","XYZ","Single"])