我有这个问题,我试图在服务有促销时获得所有美容沙龙,但服务有自定义方法并返回true或false,这是我的代码的结构
class BeautySalon < ActiveRecord::Base
has_many :services
end
class Service < ActiveRecord::Base
belongs_to :beauty_salon
has_many :service_promotions
has_many :promotions, through: :service_promotions
def has_promotion?
## consult another tables and return true or false if found a promotion
end
end
我试图像这样进行查询
BeautySalon.all.includes(:services).select('services.*').select{|service| service.has_promotion?}
但是rails返回此错误
NoMethodError(#BeautySalon的未定义方法`has_promotion?':0x0055a1119d1f40)
对此有何建议?
更新
方法has_promotion这样做
def has_promotion?
if promotions.exists?
if get_promotions(Date.today).exists?
return true
else
return false
end
end
return false
end
def get_promotions(date)
if promotions.exists?
promotions.where('start_date <= ? and end_date >= ?',date,date)
end
end
还有另一张表
class Promotion < ActiveRecord::Base
validates :discount, presence: true
validates :start_date, presence: true
validates :end_date, presence: true
has_many :service_promotions
has_many :services, through: :service_promotions
end
class ServicePromotion < ActiveRecord::Base
validates :service_id, presence:true
validates :promotion_id, presence:true
belongs_to :service
belongs_to :promotion
end
感谢所有建议
答案 0 :(得分:0)
BeautySalon.joins(:services).select { |beauty_salon| beauty_salon.services.any?(&:has_promotion?) }
这是一个选项。你现在正在调用has_promotion?在错误的对象(例如美容院而不是服务)上引发错误,因为实例方法是在Service.rb中定义的。
我认为在您的服务表中添加数据库列has_promotion(boolean)会更好。
BeautySalon.joins(:services).where(has_promotion: true)
如果has_promotion?只需从另一个相关模型中检索数据(other_association,使用db boolean column promotion),你也可以这样做:
BeautySalon.joins(services: other_association).where(other_association: { promotion: true })
更新:
BeautySalon.joins(services: :promotions).where("promotions.start_date <= :date AND promotions.end_date >= :date", date: Date.current )
这将使所有美容院恢复正常运行(今天)。