找到与另一个匹配的记录(来自另一个表)

时间:2017-12-15 23:47:44

标签: ruby-on-rails ruby

我有三个表usereventexpected_event

  • 我的event被废弃(每天都有佣金任务) 网站
  • user可以创建expected_event

所以我想做的是: 找到新的event后,我希望将其与用户expected_event进行比较... 如果event与任何用户expected_event匹配,则用户会收到一封匹配event (event.department, event.location_name)

的电子邮件

我想将 event.department expected_event.department 进行比较

我不知道怎么做......

expected_event.rb

class ExpectedEvent < ApplicationRecord
  belongs_to :user
  validates :department, presence: true
end

user.rb

class User < ApplicationRecord
  has_many :expected_events
end

事件模型中,我有一些方法可以检索city_namelocation_namedepartment

  class Event < ApplicationRecord
     def department
       self.city[/\(.*?\)/].gsub(/[()]/, "").to_i
     end

     def city_name
       self.city[/^[^\(]+/].rstrip!
     end

     def location_name
       self.city[/\|(.*)/].gsub("|", "").strip
     end
  end 

schema.rb

ActiveRecord::Schema.define(version: 20171210203403) do

  create_table "events", force: :cascade do |t|
    t.datetime "date"
    t.string   "city"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "nickname"
    ####
  end

  create_table "expected_events", force: :cascade do |t|
    t.integer  "department"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_expected_events_on_user_id"
  end

end

修改

如果我将这样的内容添加到我的用户模型中,它是否正确?

  has_many :matching_events, through: :events, source: :expected_events

1 个答案:

答案 0 :(得分:0)

创建新活动时,为什么不用查询匹配参数的ExpectedEvent条记录。像

这样的东西
event = Event.create(event_params)

if ExpectedEvent.where(city: event.city, ...).any?
  #send email to user about the event
end