我有一個名爲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
他必須包含EventProduct,否則它將在產品表中查找他沒有的event_id。 –
謝謝@LeoCorrea。你是對的。我已經更新了我的答案。 – melekes
@antonk我添加了hm關聯,但是當在控制檯中運行命令時,我仍然在產品表中查找事件ID時收到錯誤。 – Dean