0

我正在尝试为我的网站使用邀请。我想知道;我的第一个用户不需要邀请?我怎样才能破例?我可以猜到,我必须使用救援异常,但我不知道必须在哪里完成?我的 users.rb 模型:

class User < ActiveRecord::Base
  attr_accessible :nickname, :email, :password, :password_confirmation, :invitation_token
  has_secure_password
  has_many :friendships
    has_many :friends, :through => :friendships
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
    has_many :inverse_friends, :through => :inverse_friendships, :source => :user

  has_many :topics, dependent: :destroy
  has_many :posts, dependent: :destroy

  before_save { |user| user.email = email.downcase }
  before_save { |user| user.nickname = nickname.downcase }
  before_save :create_remember_token

  validates :nickname, presence: true, length: { maximum: 150 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true,
                                        format: { with: VALID_EMAIL_REGEX },
                                        uniqueness: {case_sensitive: false }

    validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true

    validates_presence_of :invitation_id, :message => 'gerekli'
    validates_uniqueness_of :invitation_id
    has_many :sent_invitations, :class_name => 'Invitation', :foreign_key => 'sender_id'
    belongs_to :invitation

    before_create :set_invitation_limit

    def invitation_token
        invitation.token if invitation
    end

    def invitation_token=(token)
        self.invitation = Invitation.find_by_token(token)
    end

    private

    def create_remember_token
        self.remember_token = SecureRandom.urlsafe_base64
    end

    def set_invitation_limit
        self.invitation_limit = 5
    end
end

这是 users_controller.rb:

def new
  @user = User.new(:invitation_token => params[:invitation_token])
  @user.email = @user.invitation.recipient_email if @user.invitation
end

   def create
    @user = User.new(params[:user])
    if @user.save
      sign_in @user
      flash[:success] = "Giripedia'ya hoşgeldiniz'!"
      redirect_to @user
    else
      render 'new'
    end
  end
4

2 回答 2

2

进行条件验证。让我给你一个简短的例子:

class User
  # ...
  validates_presence_of :invitation_id, :if => :invitation_needed?

  # An invitation is needed if there is at least one user. If there
  # are no users, there can't be an invitation.
  def invitation_needed?
    User.all.count >= 1
  end
end

详细信息:参见条件验证手册

于 2012-07-02T12:52:54.853 回答
1

我不确定为了保存您的第一个用户而编写条件验证是否是个好主意。

您不想在每次验证用户时都进行计数查询。

您可以使用跳过验证选项从控制台保存您的第一个用户。

@user.save(:validate => false)
于 2012-07-02T20:31:26.280 回答