未定义的方法`map' for nil:NilClass Sunspot has_one association

时间:2014-01-16 19:45:22

标签: ruby-on-rails sunspot

我有一个表用户,它有一个common_app。我想在用户的common_app.cover_letter中制作文本,可以搜索。

当我尝试这样做时,我收到错误 -

rake sunspot:reindex
undefined method `map' for nil:NilClass
/Users/stepan/Desktop/Previous Desktop/Sites/atlas/app/models/user.rb:45:in `block (2 levels) in <class:User>'

这就是我的用户模型的样子 -

# == Schema Information
#
# Table name: users
#
#  id                     :integer          not null, primary key
#  name                   :string(255)
#  email                  :string(255)
#  created_at             :datetime
#  updated_at             :datetime
#  password_digest        :string(255)
#  remember_token         :string(255)
#  admin                  :boolean          default(FALSE)
#  password_reset_token   :string(255)
#  password_reset_sent_at :datetime
#  heat_id                :integer
#

class User < ActiveRecord::Base
  before_save { self.email = email.downcase }
  before_create :create_remember_token

  validates :name, presence: true, length: { maximum: 50 }
  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 }

  has_secure_password validations: false

  validates :password, length: { minimum: 6 }, allow_blank: true
  validates :password, presence: true, on: :create

  belongs_to :heat

  has_one :common_app, dependent: :destroy

  has_one :video, dependent: :destroy

  has_many :applications, dependent: :destroy
  has_many :jobs, :through => :applications

  searchable do 
    text :name, :email
    text :common_app do
      common_app.map { |common_app| common_app.cover_letter }
    end
  end

  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.encrypt(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    save!
    UserMailer.password_reset(self).deliver
  end

  def generate_token(column) # this is similar to create_remember_token, but instead it's generalized, so it can work on any column
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while User.exists?(column => self[column])
  end

  def beginner? 
    false if self.common_app || self.video || self.jobs.any?
  end

  def first_name
    self.name.split(' ')[0].capitalize
  end

  private

    def create_remember_token
      self.remember_token = User.encrypt(User.new_remember_token)
    end

end

我猜这种情况正在发生,因为有些用户没有common_app,或者我错误地引用了has_one关联。

非常感谢!

1 个答案:

答案 0 :(得分:1)

我认为这应该有用。

  text :common_app do
    common_app.cover_letter
  end

这是一个has_one关系,这意味着你无法映射它。如果是has_many :common_apps关系,您可以映射。