加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 多对多关系的活动记录查询

发布时间:2020-12-17 02:36:34 所属栏目:百科 来源:网络整理
导读:我有一个名为Event的模型和另一个名为Product的模型.事件有很多产品,产品有很多事件(通过名为Eventproduct的连接模型).我正在尝试设计一个查询,它将选择当前日期范围内与其他事件不匹配的所有产品,因此当用户创建具有日期范围的事件时,它将显示可用的产品,以
我有一个名为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,: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,: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

解决方法

我想出了一个可以帮助你的查询.你必须计算时间范围的条件和它的逻辑.

查询看起来应该是这样的

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")

这应该返回所有不符合您条件的产品,包括那些尚未发生事件的产品.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读