我正在做一个纸追逐/寻宝移动网络应用程序。我有基本的身份验证,如果用户扫描以下任何代码,他将被定向到sign_up页面。到目前为止,一切都很好,但这里有一个棘手的部分:
我有10个QR码,每一个都代表一个URL.
代码ID:1 URL:http://paperchase.heroku.com/qrs/4975
现在,我希望用户按照显示的顺序扫描每一段代码。如果他扫描代码1,他将找到代码2的方向,如果他扫描代码2,他将找到代码3的指示,等等。但是现在有可能跳过代码,例如,你可以在代码1之后扫描代码10并获胜。
--我想出的解决方案:
所有QR码都被设置为false。如果你扫描QR-代码1,它将被设置为真,你可以扫描QR-代码2。如果你现在要扫描QR-代码5,它会将你重定向到root_path,因为QR-代码4被设置为false。
这是我的用户模型的一部分:
...
t.boolean :qr_01, :default => false
t.boolean :qr_02, :default => false
t.boolean :qr_03, :default => false
t.boolean :qr_04, :default => false
...
现在,我认为我必须用逻辑编写某种before_filter
(将QR-代码设置为true,检查是否所有先前的QR-代码都设置为真),但我不知道它应该是什么样的。
提前感谢
发布于 2011-06-14 19:35:57
为什么不在模型中存储一个int字段呢?
例如,如果我的用户模型
t.integer :qr_code
您可以简单地检查控制器操作的内部:
def add_qr
user = User.find_by_id(params[:id])
if user.qr_code != params[:qr_code]-1
redirect_to(some_url)
else
user.qr_code+=1
user.save
#do whatever else you need to do and display view
end
end
发布于 2011-06-14 18:36:02
我认为您正在尝试将您的验证放在错误的位置,您的模式可能需要进行一些调整。
如果有人正在输入QR4,您真的关心他们是否已经通过QR3输入了QR1,还是只关心他们输入的最后一个是QR3?在输入新代码时,真正重要的是在最后一个代码之后立即执行;并且,为了使事情一致,您可以使用一个虚拟的QR0来表示“尚未进入”状态。
在您的用户模型中,应该有这样的方法:
def add_code(qr)
# Check that qr immediately follows self.last_qr;
# if it does, then update and save things and
# continue on; if it doesn't, then raise an
# exception that says, more or less, "QR Code out
# of sequence".
end
您可以跟踪用户模型中的最后代码和当前代码,并使用验证钩子确保它们正常:
before_create :initialize_qrs
validate :contiguous_qrs
#...
def initialize_qrs
self.last_qr = 0
self.latest_qr = 0
end
def contiguous_qrs
if(self.last_qr == 0 && self.latest_qr == 0)
# New user, no worries.
true
elsif(self.latest_qr != self.last_qr + 1)
# Sequence error, your `add_code` method should
# prevent this from ever happening but, hey, bugs
# happen and your code shouldn't trust itself any
# more than it has to.
false
end
true
end
add_code
方法在执行其他工作时会设置self.last_qr
和self.latest_qr
。
然后,在你的控制器上:
def enter_code
# Get the code and validate it, leave it in qr
begin
current_user.add_code(qr)
rescue Exception => e
# Complain and wag your finger at them for cheating
end
# Give them instructions for finding the next one,
# these instructions would, presumably, come from
# something like "instructions = qr.next_one.instructions".
end
跟踪(用户,QR)对对于审计而言是有意义的,但对于我来说,有一个单独的模型(作为关联表)对此更有意义:
create table "user_qr_codes" do |t|
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id", :null => false
t.integer "qr_code_id", :null => false
end
然后以通常的方式将该关联与用户和QrCode模型链接起来。
还要注意的是,这个结构只需要几个简单的修改就可以同时运行多个“纸追逐”。您只需要将用户模型中的一些内容移动到user_paper_chases
模型中,并向User#add_code
添加一个paper_chase
参数。
没有规则说您的用户界面必须是数据模型属性的简单编辑器,并且像这样紧密地将两者绑定在一起通常是一个错误(这是一个非常常见的错误,但仍然是一个错误)。
https://stackoverflow.com/questions/6347635
复制相似问题