未定义的方法`first_name'为零:NilClass

时间:2013-09-22 22:38:49

标签: ruby-on-rails ruby ruby-on-rails-3 elasticsearch tire

我使用Tire和ElasticSearch实现了搜索 - 一切都运行良好。

我有三种模式:帖子,出版物和用户。用户通过出版物有很多帖子。

使用轮胎,我已经发布了可搜索的帖子。但是,我现在希望Posts和Post的用户可以搜索。这就是事情破裂的地方。

以下是我的帖子模型:

class Post < ActiveRecord::Base
  attr_accessible :description, :name, :tag_list, :thumbnail_image, :status, :post_type, :subtitle, :summary, :visibility, :user
  acts_as_taggable

  has_one :publication
  has_one :user, :through => :publication
  has_many :subscriptions, dependent: :destroy


  has_many :channel_post_connections, dependent: :destroy
  has_many :channels, :through => :channel_post_connections

  accepts_nested_attributes_for :channel_post_connections
  accepts_nested_attributes_for :channels
  accepts_nested_attributes_for :publication
  accepts_nested_attributes_for :user


  has_many :post_pages, dependent: :destroy

  validates_presence_of :post_type, :name, :subtitle, :tag_list, :summary, :thumbnail_image, :if => :post_is_published?


  include Tire::Model::Search
  include Tire::Model::Callbacks
  index_name 'posts_index'


  def self.search(params)
    tire.search(load: true) do
        query { string params[:query], default_operator: "AND" } if params[:query].present? 
      sort { by :created_at, "desc" } if params[:query].blank?
    end
  end

  def to_indexed_json
    to_json(methods: [:user_first_name, :user_display_name])
  end

  def user_first_name
    user.first_name
  end

  def user_display_name
    user.display_name
  end

end

在to_indexed_json方法中似乎崩溃了,这是我在尝试创建新帖子时收到的错误:

NoMethodError in PostsController#create
undefined method `first_name' for nil:NilClass

我不确定为什么会发生这种情况 - 类应该是“User”,并且first_name是Users表中的有效列,具有合法值。

任何帮助将不胜感激!

0 个答案:

没有答案