Ruby on rails 你如何让一个对象观察/订阅它自己来观察某个字段?
在我的《观察者》中,我试图为一个产品编写一个方法,让它“审视自身”,然后找到与Ruby on rails 你如何让一个对象观察/订阅它自己来观察某个字段?,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-3.1,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 3.1,在我的《观察者》中,我试图为一个产品编写一个方法,让它“审视自身”,然后找到与:price字段唯一不同的相同产品。换句话说,我试图通知用户,如果他们订阅了价格更低的产品 这是我的产品表: create_table :products do |t| t.string :name t.decimal :price t.integer :user_id t.integer :store_id t.boolean :watch_price end 然后我有了我的观察者: clas
:price
字段唯一不同的相同产品。换句话说,我试图通知用户,如果他们订阅了价格更低的产品
这是我的产品表:
create_table :products do |t|
t.string :name
t.decimal :price
t.integer :user_id
t.integer :store_id
t.boolean :watch_price
end
然后我有了我的观察者:
class ProductObserver < ActiveRecord::Observer
def after_update(product)
if product.watch_price
end
end
end
class ProductObserver
因此,如果布尔值:watch_price
为真,则用户已订阅该产品。我把它放在更新(产品)后的中,因为我希望用户能够选中查看价格
复选框,然后它立即在数据库上执行Cron操作,然后每小时执行一次
我遇到的问题是让一个产品自我评估并搜索完全相同的产品,唯一的区别是:price
字段。如何做到这一点
提前感谢,新手可能需要一些帮助 我认为您需要一个HMT产品模型来跟踪哪些用户正在跟踪哪些产品。在该模型中,您可以保留他们关注的价格和产品名称的属性
您可以使用该模型每小时搜索具有相同名称的较低价格的产品,然后通知用户
# Model
class WatchedProduct < ActiveRecord::Base
belongs_to :user
belongs_to :product
# attributes name, price
end
# CRON/Rake task
for watched_product in WatchedProduct.all
for product in Product.find_by_name(watched_product.name)
if watched_product.price > product.price
# notify user
# update the new watched price of the cheaper product
end
end
end
#模型
类WatchedProduct产品价格
#通知用户
#更新更便宜产品的新价格
结束
结束
结束
显然,可以进行更多的优化,但你明白了
您可能希望使用另一个cron作业使关注的产品过期。设置订阅机制/关系。为了提高下面示例的性能以及使其更加模块化,我们可以做很多工作,但您应该明白这一点
app/models/product.rb
类产品:subscriptions,:class\u name=>'User'
结束
app/models/user.rb
class用户:订阅
def通知价格下降(产品、原价)
#不知怎么通知
结束
结束
app/models/subscription.rb
类订阅“用户”
结束
app/models/product_observer.rb
class ProductObserver
class Product < ActiveRecord::Base
has_many :subscriptions
has_many :subscribers, :through => :subscriptions, :class_name => 'User'
end
class User < ActiveRecord::Base
has_many :subscriptions
has_many :products, :through => :subscriptions
def notify_of_price_drop(product, original_price)
# notify somehow
end
end
class Subscription < ActiveRecord::Base
# be sure to add snapshot_price field to the subscriptions table in your migration
belongs_to :product
belongs_to :subscriber, :class_name => 'User'
end
class ProductObserver < ActiveRecord::Observer
def after_update(product)
product.subscriptions.each do |subscription|
if subscription.snapshot_price < product.price
subscription.user.notify_of_price_drop(product, subscription.snapshot_price)
end
end
end
end