【问题标题】:Rails ActiveRecord Query (Cross model)Rails ActiveRecord 查询(跨模型)
【发布时间】:2012-06-26 16:53:52
【问题描述】:

我有一个应用程序,可让用户输入与这些日期相关的日期和兴趣。我需要根据他们的兴趣和位置向他们发送交易(日期前几天 - 通过电子邮件)。我已经正确设置了所有模型并记录了数据,只是想知道如何查询模型的日期,然后根据城市和兴趣发送适当的交易。

注意事项:

*每个城市和兴趣类别只有 1 笔交易

*对于日期类型(假期、场合、朋友生日等),我有几种不同的模型.. 在结构上几乎相同。

*每种日期的所有兴趣都存储在 person_interests 中。

    Models:

    Class User
      belongs_to :province
      belongs_to :city
      has_many :friends_bdays
      has_many :occasions
      has_many :person_interests, :as => :person
      has_many :interests, :through => :person_interests
      has_many :user_holidays
      has_many :holidays, :through => :user_holidays
      has_many :anniversaries
    end

    class Deal < ActiveRecord::Base
       belongs_to :interest
       belongs_to :city
       belongs_to :store  
    end

   class Store < ActiveRecord::Base
      has_many :deals
      belongs_to :city
      belongs_to :province
    end

    class PersonInterest < ActiveRecord::Base
      belongs_to :interest
      belongs_to :person, :polymorphic => true  
    end

    class Interest < ActiveRecord::Base
      has_many :person_interests
      has_many :deals
    end


    class Occasion < ActiveRecord::Base
      belongs_to :user
      belongs_to :admin_user
      has_many :person_interests, :as => :person
      has_many :interests, :through => :person_interests    
    end


    class Anniversary < ActiveRecord::Base
      belongs_to :user
      has_many :person_interests, :as => :person
      has_many :interests, :through => :person_interests
    end


  class Friend_bday < ActiveRecord::Base
    belongs_to :user
    has_many :person_interests, :as => :person
    has_many :interests, :through => :person_interests
  end

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    您可以使用以下解决方案的变体来实现此目的:

    安装squeel gem

    class User
      def deals(reload=false)
        @deals = nil if 
        @deals ||= Deal.where{ 
         ( (:city => city_id) | ( :interest_id => interest_ids) ) & 
         :deal_date => (Time.now..3.days.from_now) 
        }
      end
    end
    

    现在,user.deals 返回与用户的城市或兴趣相匹配的未来 3 天内有效的交易。

    编辑 1:

    根据您的评论,您似乎不需要 squeel gem。您可以使用常规 AR 语法实现您想要的。

    class User
      def deals(reload=false)
        @deals = nil if reload
    
        @deals ||= Deal.where(
          :city => city_id, 
          :interest_id => interest_ids, 
          :deal_date => (Time.now..3.days.from_now) 
        )
      end
    end
    

    【讨论】:

    • 谢谢!...我怎么能做用户城市和兴趣...交易属于(城市和兴趣)所以如果用户来自城市(A)并且有兴趣(A) (B)(C) 他/她将获得这 3 个独特的交易..
    • 我遇到的问题是“:deal_date”.. 这些不是每个人说的交易日期.. 日期基于用户在场合、朋友生日或周年纪念模型中输入的内容(上面列出的)..所以属性需要来自这些模型..我该怎么做?
    • 就像我需要运行 user.friend_bday.deals 等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多