2012-07-02 38 views
4

我有一個名爲Event的模型,另一個名爲Product。一個事件有很多產品,一個產品有許多事件(通過名爲Eventproduct的連接模型)。我試圖設計一個查詢來選擇當前日期範圍與另一個事件不匹配的所有事件,因此當用戶創建具有日期範圍的事件時,它將顯示可用的產品,以便同一產品不能同時在2個事件中。這可能與活動記錄查詢接口,或者我需要寫我自己的特定SQL查詢。多對多關係的活動記錄查詢

我遷移的樣子:

class CreateProducts < ActiveRecord::Migration 
    def change 
    create_table :products do |t| 
     t.string :make 
     t.string :model 
     t.integer :wattage 
     t.boolean :dmx 
     t.decimal :price 
     t.timestamps 
    end 
    end 
end 


class CreateEvents < ActiveRecord::Migration 
    def change 
    create_table :events do |t| 
     t.datetime :start_date 
     t.datetime :end_date 
     t.timestamps 
    end 
    end 
end 


class AddContactToEvent < ActiveRecord::Migration 
    def change 
    add_column :events, :name, :string 
    add_column :events, :location, :string 
    add_column :events, :contact_number, :string 
    end 
end 

class CreateEventproducts < ActiveRecord::Migration 
    def change 
    create_table :eventproducts do |t| 
     t.references :product 
     t.references :event 

     t.timestamps 
    end 
    add_index :eventproducts, :product_id 
    add_index :eventproducts, :event_id 
    end 
end 

以下是相關車型:

class Event < ActiveRecord::Base 
    attr_accessible :end_date, :start_date, :products, :lightings, :name, :location, :contact_number, :product_ids 
    has_many :products, :through => :Eventproduct 
    has_many :Eventproduct 
    validates_presence_of :name, :message => "can't be blank" 
    validates_presence_of :location, :message => "can't be blank" 
    validates_presence_of :contact_number, :message => "A telephone number is needed so that we can contact you if we have any problems" 
    validates_presence_of :start_date, :message => "can't be blank" 
    validates_presence_of :end_date, :message => "can't be blank" 
end 

class Eventproduct < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :event 
    # attr_accessible :title, :body 
end 


class Product < ActiveRecord::Base 
    validates :price, numericality: {greater_than_or_equal_to: 0.01} 
    attr_accessible :make, :model, :wattage, :dmx, :price 
end 

回答

2

我想出了一個可以幫助您的查詢。你必須弄清楚時間範圍的條件和邏輯。

查詢應該是這個樣子

Product.joins(:events).where("events.start_date <= :start_date", {start_date: Time.now}) 

where子句應該包含你的邏輯來過濾不需要的事件。再次,這段代碼應該讓你開始。所以要回答你的問題,這是可能的。查看您獲得的查詢並解決此問題,以制定符合您需求的條件。另外,看看這個鏈接,這應該幫助你修改where子句的方式,我做了: http://guides.rubyonrails.org/active_record_querying.html

希望這可以幫助你!

更新:

您可能需要做一個Product.all以及一些差集,包括那些沒有在事件所有這些產品,因爲查詢將返回空,如果產品不具備EventProduct表中的事件。它可能效率不高,但它應該取決於你所需要的。

Product.all - Product.joins(:events).where("condition reversed") 

這應該返回所有不符合條件的產品,包括那些還沒有事件的產品。

3

試試這個:Product.includes(:Eventproduct).where(eventproducts: { event_id: nil }).group('products.id')

注意它是where條件中表的名稱。另外不要忘記添加Eventproduct關聯到您的產品型號:has_many :Eventproduct

+2

他必須包含EventProduct,否則它將在產品表中查找他沒有的event_id。 –

+0

謝謝@LeoCorrea。你是對的。我已經更新了我的答案。 – melekes

+0

@antonk我添加了hm關聯,但是當在控制檯中運行命令時,我仍然在產品表中查找事件ID時收到錯誤。 – Dean