Rails 要求使用密钥来创建模型 [英] Rails asking for a secret key to create model

查看:69
本文介绍了Rails 要求使用密钥来创建模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个没有用户身份验证系统的简单博客/新闻网站.我决定使用简单的某种密钥检查技术,让知道密钥的访问者发帖.

I am creating a simple blog / news website without a user authentication system. I've decided to a use plain some sort of secret key checking technique to allow visitors who know the key to make posts.

简而言之,要发布,您必须提供密钥.否则,不应将 it 对象保存到数据库中.

In short, to post, you have to provide a key. Otherwise, it object should not be saved into the db.

这是我的代码.

class Post < ActiveRecord::Base

  attr_accessor :slaptazodis

  validate :passcheck
  validates :title, presence: true
  validates :body, presence: true

  def passcheck

    if :slaptazodis != "1234"
      errors.add(:base, 'Invalid pass')
    end
  end
end

因此,我在沙箱中创建了一个新模型,标题、正文和属性 slaptazodis 设置为 1234.不过,当我检查错误时,控制台一直显示无效通过".我究竟做错了什么?是关于属性还是什么?提前谢谢你:)

So, I create a new model in sandbox with title, body and attribute slaptazodis set to 1234. Still, when I check errors, console keeps showing me "Invalid pass". What am I doing wrong? Is it about attributes or something? Thank you in advance :)

推荐答案

您应该考虑将该逻辑从后期模型中移出并将其移至控制器.

You should consider putting that logic away from the post model and moving it to the controller.

在控制器中,您可以检查用户发送的参数,例如.

In the controller you could check the parameters sent by an user eg.

if params[:slaptazodis] != "1234"

但是,如果您正在学习 Rails 并且只想使其与您现有的解决方案一起使用,请更改:

If however, you're learning rails and just want to make it work with your existing solution, change from:

if :slaptazodis != "1234"

到:

if slaptazodis != "1234"

:"告诉 Rails 它应该考虑 symbol 后面的字符(几乎与字符串相同)只是为了澄清,因此您的代码几乎同说:

The ":" tells Rails that it should consider the characters following a symbol (almost the same as a string) just for clarification, your code is therefore almost the same as say:

if "slaptazodis" != "1234"

这当然总是正确的.

这篇关于Rails 要求使用密钥来创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆