문제

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.

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

Here's my code.

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

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"

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

if :slaptazodis != "1234"

to:

if slaptazodis != "1234"

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"

Which of course always renders true.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top