Ruby on Rails,创建方法

时间:2011-07-30 22:09:14

标签: ruby-on-rails ruby

我正在尝试创建一个在创建任何新用户后运行的方法。自从我使用红宝石以来已经有一段时间了,所以我遇到了一些麻烦。

我收到此错误 C:/Users/antarr/SeniorProject/app/models/user.rb:9:语法错误,意外的tASSOC,期待keyword_then或';'或'\ n'

class User < ActiveRecord::Base

  acts_as_authentic
  after_create :set_universal
  after_create :set_carrier
  after_create :set_role

  def set_role
    if User.count >= 1
      endself.roles << "admin"
    else
      self.roles << "subscriber"
    end
  end

  def set_universal
    if Channel.find(1).exist
      self.channels << Channel.find(1)
  end

  def set_carrier
    self.carrier = Carrier.with_name(self.carrier_name).first
  end

  ROLES = %w[admin  moderator subscriber]

  #Each user can subscribe to many channels
  has_and_belongs_to_many :channels

  #Each user who is a moderator can moderate many channels
  #has_many :channel_mods
  has_and_belongs_to_many :modifies , :class_name => "Channel"

  #Each user can receive many messages
  has_and_belongs_to_many :messages

  #Each user belongs to a carrier
  belongs_to :carrier

  #Filter users by role(s)
  named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0 "} }

  def roles  
    ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }  
  end

  def roles=(roles)  
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum  
  end

  def role_symbols
  roles.map do |role|
    role.underscore.to_sym  # NOT role.name.underscore.to_sym (role is a string)
    end
  end


end

2 个答案:

答案 0 :(得分:4)

您的操作符错误,它是>=,而不是=>=>是Hashes的运算符。

def set_role
  if User.count >= 1
    self.roles << "admin"
  else
    self.roles << "subscriber"
  end
end

答案 1 :(得分:3)

“Hash rockets”(=>)用于Ruby中的哈希,你需要>=

...
if User.count >= 1
...