I've implemented search using Tire and ElasticSearch – everything has been working great.
I have three models: Posts, Publications and Users. Users have many Posts through Publications.
Using tire, I've made Posts searchable. However, I now want the Posts and the Post's user to be searchable. This is where things break.
Below is my Post model:
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
Things seem to fall apart at the to_indexed_json method, here's the error I receive when I try to create a new post:
NoMethodError in PostsController#create
undefined method `first_name' for nil:NilClass
I'm not certain why this is happening – the Class should be "User", and, first_name is a valid column in the Users table, with a legitimate value.
Any help would be appreciated!