jam-cloud/lib/jam_ruby/models/band.rb

133 lines
3.4 KiB
Ruby

module JamRuby
class Band < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
attr_accessible :name, :website, :biography
self.primary_key = 'id'
# musicians
has_many :band_musicians
has_many :users, :through => :band_musicians, :class_name => "JamRuby::User"
# genres
has_and_belongs_to_many :genres, :class_name => "JamRuby::Genre", :join_table => "bands_genres"
after_save :limit_to_three_genres
def photo_url
# TODO: move image path to config
@photo_url = "http://www.jamkazam.com/images/bands/photos/#{self.id}.gif"
end
def logo_url
# TODO: move image path to config
@logo_url = "http://www.jamkazam.com/images/bands/logos/#{self.id}.gif"
end
def location
# TODO: implement a single string version of location;
# this will be indexed into elasticsearch and returned in search
return "Austin, TX"
end
# helper method for creating / updating a Band
def self.save(params)
if params[:id].nil?
band = Band.new()
else
band = Band.find(params[:id])
end
# name
unless params[:name].nil?
band.name = params[:name]
end
# name
unless params[:website].nil?
band.website = params[:website]
end
# name
unless params[:biography].nil?
band.biography = params[:biography]
end
# genres
genres = params[:genres]
unless genres.nil?
ActiveRecord::Base.transaction do
# delete all genres for this band first
unless band.id.nil? || band.id.length == 0
band.genres.delete_all
end
# loop through each instrument in the array and save to the db
genres.each do |genre_id|
g = Genre.find(genre_id)
band.genres << g
end
end
end
band.updated_at = Time.now.getutc
band.save
return band
end
def limit_to_three_genres
if self.genres.count > 3
errors.add(:genres, "No more than 3 genres are allowed.")
end
end
### Elasticsearch/Tire integration ###
#
# Define the name based on the environment
# We wouldn't like to erase dev data during
# test runs!
#
index_name("#{Environment.mode}-#{Environment.application}-bands")
def to_indexed_json
{
:name => name,
:logo_url => logo_url,
:photo_url => photo_url,
:location => location
}.to_json
end
class << self
def create_search_index
Tire.index(Band.index_name) do
create(
:settings => Search.index_settings,
:mappings => {
"jam_ruby/band" => {
:properties => {
:logo_url => { :type => :string, :index => :not_analyzed, :include_in_all => false },
:photo_url => { :type => :string, :index => :not_analyzed, :include_in_all => false},
:name => { :type => :string, :boost => 100},
:location => { :type => :string },
}
}
}
)
end
end
def delete_search_index
search_index.delete
end
def search_index
Tire.index(Band.index_name)
end
end
### Elasticsearch/Tire integration
end
end