我正在尝试为我的网站使用邀请。我想知道;我的第一个用户不需要邀请?我怎么能例外?我可以猜到, 我必须使用救援例外,但我不知道必须在哪里完成? 我的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
答案 0 :(得分: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
详细信息:请参阅conditional validation
上的手册答案 1 :(得分:1)
我不确定为了能够保存您的第一个用户而编写条件验证是否是一个好主意。
每次验证用户时,您都不想进行计数查询。
您可以使用跳过验证选项从控制台保存您的第一个用户。
@user.save(:validate => false)