如何通过字段find_or_create_by
编写Clicks
方法来创建或查找clicktime
,因此在24小时内创建的点击是唯一的?
创建方法:
description = Description.find(params[:id])
click = description.clicks
.find_or_create_by(clicktime: ___ )
Click.increment_counter(:count, click.id)
显示方法:
@descriptions = Description.includes(:clicks)
.where(:clicks => { clicktime: (Time.now - 24.hours)..Time.now })
.order('count DESC')
答案 0 :(得分:0)
您可以使用first_or_create
代替find_or_createclick = description.clicks.where(clicktime: ___ ).first_or_create
答案 1 :(得分:0)
description = Description.find(params[:id])
click = description.clicks.
find_by(clicktime: (Time.now - 24.hours)..Time.now)
if click != nil
Click.increment_counter(:count, click.id)
else
new_click = description.clicks.create(clicktime: Time.now)
Click.increment_counter(:count, new_click.id)
end