how to check status new in activescaffold - ruby-on-rails

active_scaffold :formats do |config|
format_order = Format.find(:all, :select => :format_order, :order => :format_order).collect(&:format_order)
format_order << format_order.size + 1 # I want only implement when new
config.columns = [:name, :format_order]
config.columns[:format_order].form_ui = :select
config.columns[:format_order].options = {
:options => format_order
}
config.list.columns = [:name, :format_order]
end
I want if I new format, format_order will add a number as code (format_order.size + 1) but I don't want implement it for edit. please help me. thanks

You will have to implement a callback:
class Format < ActiveRecord::Base
...
after_validation(:on => :create) do
self.code = whatever_code_you_want_to_assign #
end
...
end

Related

Ruby - PG::UndefinedTable: ERROR: missing FROM-clause entry for table

I'm getting the following error when I'm trying to query another table in a model definition.
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "miq_user_roles" LINE 1: ..." = $1 AND "service_templates"."display" = $2 AND "miq_user_... ^ [catalog/explorer]
Any idea how to resolve this?
scope :with_service_template_catalog_id, ->(cat_id) { where(:service_template_catalog_id => cat_id) }
scope :without_service_template_catalog_id, -> { where(:service_template_catalog_id => nil) }
scope :with_existent_service_template_catalog_id, -> { where.not(:service_template_catalog_id => nil) }
scope :displayed, -> { where(:display => true) }
scope :public_service_templates, -> { where("miq_user_roles.settings" => nil) }
Here is the full code:
class ServiceTemplate < ApplicationRecord
include SupportsFeatureMixin
DEFAULT_PROCESS_DELAY_BETWEEN_GROUPS = 120
GENERIC_ITEM_SUBTYPES = {
"custom" => N_("Custom"),
"vm" => N_("Virtual Machine"),
"playbook" => N_("Playbook"),
"hosted_database" => N_("Hosted Database"),
"load_balancer" => N_("Load Balancer"),
"storage" => N_("Storage")
}.freeze
SERVICE_TYPE_ATOMIC = 'atomic'.freeze
SERVICE_TYPE_COMPOSITE = 'composite'.freeze
RESOURCE_ACTION_UPDATE_ATTRS = [:dialog,
:dialog_id,
:fqname,
:configuration_template,
:configuration_template_id,
:configuration_template_type].freeze
include CustomActionsMixin
include ServiceMixin
include OwnershipMixin
include NewWithTypeStiMixin
include TenancyMixin
include ArchivedMixin
include CiFeatureMixin
include_concern 'Filter'
include_concern 'Copy'
validates :name, :presence => true
belongs_to :tenant
has_many :service_templates, :through => :service_resources, :source => :resource, :source_type => 'ServiceTemplate'
has_many :services
has_many :service_template_tenants, :dependent => :destroy
has_many :additional_tenants, :through => :service_template_tenants, :source => :tenant, :dependent => :destroy
has_one :picture, :dependent => :destroy, :as => :resource, :autosave => true
belongs_to :service_template_catalog
belongs_to :zone
belongs_to :currency, :inverse_of => false
has_many :dialogs, -> { distinct }, :through => :resource_actions
has_many :miq_schedules, :as => :resource, :dependent => :destroy
has_many :miq_requests, :as => :source, :dependent => :nullify
has_many :active_requests, -> { where(:request_state => MiqRequest::ACTIVE_STATES) }, :as => :source, :class_name => "MiqRequest"
virtual_column :type_display, :type => :string
virtual_column :template_valid, :type => :boolean
virtual_column :template_valid_error_message, :type => :string
virtual_column :archived, :type => :boolean
virtual_column :active, :type => :boolean
default_value_for :internal, false
default_value_for :service_type, SERVICE_TYPE_ATOMIC
default_value_for(:generic_subtype) { |st| 'custom' if st.prov_type == 'generic' }
virtual_has_one :config_info, :class_name => "Hash"
scope :with_service_template_catalog_id, ->(cat_id) { where(:service_template_catalog_id => cat_id) }
scope :without_service_template_catalog_id, -> { where(:service_template_catalog_id => nil) }
scope :with_existent_service_template_catalog_id, -> { where.not(:service_template_catalog_id => nil) }
scope :displayed, -> { where(:display => true) }
scope :public_service_templates, -> { where("miq_user_roles.settings" => nil) }
supports :order do
unsupported_reason_add(:order, 'Service template does not belong to a service catalog') unless service_template_catalog
unsupported_reason_add(:order, 'Service template is not configured to be displayed') unless display
end
alias orderable? supports_order?
alias validate_order supports_order?
def self.with_tenant(tenant_id)
tenant = Tenant.find(tenant_id)
where(:tenant_id => tenant.ancestor_ids + [tenant_id])
end
def self.with_additional_tenants
references(table_name, :tenants).includes(:service_template_tenants => :tenant)
end
def self.all_catalog_item_types
#all_catalog_item_types ||= begin
builtin_catalog_item_types = {
"generic" => N_("Generic"),
"generic_orchestration" => N_("Orchestration"),
}
ExtManagementSystem.subclasses_supporting(:catalog)
.flat_map(&:catalog_types)
.reduce(builtin_catalog_item_types, :merge)
end
end
def self.catalog_item_types
ems_classes = Rbac.filtered(ExtManagementSystem.all).collect(&:class).uniq.select { |ems| ems.supports?(:catalog) }
ci_types = Set.new(ems_classes.flat_map(&:catalog_types).reduce({}, :merge).keys)
ci_types.add('generic_orchestration') if Rbac.filtered(OrchestrationTemplate).exists?
ci_types.add('generic')
all_catalog_item_types.each.with_object({}) do |(key, description), hash|
hash[key] = {:description => description, :display => ci_types.include?(key)}
end
end
def self.create_catalog_item(options, auth_user)
transaction do
create_from_options(options).tap do |service_template|
config_info = options[:config_info].except(:provision, :retirement, :reconfigure)
workflow_class = MiqProvisionWorkflow.class_for_source(config_info[:src_vm_id])
if workflow_class
request = workflow_class.new(config_info, auth_user).make_request(nil, config_info)
service_template.add_resource(request)
end
service_template.create_resource_actions(options[:config_info])
end
end
end
def self.class_from_request_data(data)
request_type = data['prov_type']
if request_type.include?('generic_')
generic_type = request_type.split('generic_').last
"ServiceTemplate#{generic_type.camelize}".constantize
else
ServiceTemplate
end
end
def update_catalog_item(options, auth_user = nil)
config_info = validate_update_config_info(options)
unless config_info
update!(options)
return reload
end
transaction do
update_from_options(options)
update_service_resources(config_info, auth_user)
update_resource_actions(config_info)
save!
end
reload
end
def children
service_templates
end
def descendants
children.flat_map { |child| [child] + child.descendants }
end
def subtree
[self] + descendants
end
def vms_and_templates
[]
end
def destroy
if parent_services.present?
raise MiqException::MiqServiceError, _("Cannot delete a service that is the child of another service.")
end
service_resources.each do |sr|
rsc = sr.resource
rsc.destroy if rsc.kind_of?(MiqProvisionRequestTemplate)
end
super
end
def archive
raise _("Cannot archive while in use") unless active_requests.empty?
archive!
end
def retireable?
false
end
def request_class
ServiceTemplateProvisionRequest
end
def request_type
"clone_to_service"
end
def config_info
options[:config_info] || construct_config_info
end
def create_service(service_task, parent_svc = nil)
nh = attributes.dup
# Service#display was renamed to #visible in https://github.com/ManageIQ/manageiq-schema/pull/410
nh['visible'] = nh.delete('display') if nh.key?('display')
nh['options'][:dialog] = service_task.options[:dialog]
(nh.keys - Service.column_names + %w(created_at guid service_template_id updated_at id type prov_type)).each { |key| nh.delete(key) }
# Hide child services by default
nh['visible'] = false if parent_svc
# If visible is nil, set it to false
nh['visible'] ||= false
# convert template class name to service class name by naming convention
nh['type'] = self.class.name.sub('Template', '')
nh['initiator'] = service_task.options[:initiator] if service_task.options[:initiator]
service = Service.create!(nh) do |svc|
svc.service_template = self
set_ownership(svc, service_task.get_user)
service_resources.each do |sr|
nh = sr.attributes.dup
%w(id created_at updated_at service_template_id).each { |key| nh.delete(key) }
svc.add_resource(sr.resource, nh) unless sr.resource.nil?
end
end
service.tap do |svc|
if parent_svc
service_resource = ServiceResource.find_by(:id => service_task.options[:service_resource_id])
parent_svc.add_resource!(svc, service_resource)
end
end
end
def composite?
service_type.to_s.include?(self.class::SERVICE_TYPE_COMPOSITE)
end
def atomic?
service_type.to_s.include?(self.class::SERVICE_TYPE_ATOMIC)
end
def type_display
case service_type
when self.class::SERVICE_TYPE_ATOMIC then "Item"
when self.class::SERVICE_TYPE_COMPOSITE then "Bundle"
when nil then "Unknown"
else
service_type.to_s.capitalize
end
end
def create_tasks_for_service(service_task, parent_svc)
unless parent_svc
return [] unless self.class.include_service_template?(service_task,
service_task.source_id,
parent_svc)
end
svc = create_service(service_task, parent_svc)
service_task.destination = svc
create_subtasks(service_task, svc)
end
# default implementation to create subtasks from service resources
def create_subtasks(parent_service_task, parent_service)
tasks = []
service_resources.each do |child_svc_rsc|
scaling_min = child_svc_rsc.scaling_min
1.upto(scaling_min).each do |scaling_idx|
nh = parent_service_task.attributes.dup
%w(id created_on updated_on type state status message).each { |key| nh.delete(key) }
nh['options'] = parent_service_task.options.dup
nh['options'].delete(:child_tasks)
# Initial Options[:dialog] to an empty hash so we do not pass down dialog values to child services tasks
nh['options'][:dialog] = {}
next if child_svc_rsc.resource_type == "ServiceTemplate" &&
!self.class.include_service_template?(parent_service_task,
child_svc_rsc.resource.id,
parent_service)
new_task = parent_service_task.class.new(nh)
new_task.options.merge!(
:src_id => child_svc_rsc.resource.id,
:scaling_idx => scaling_idx,
:scaling_min => scaling_min,
:service_resource_id => child_svc_rsc.id,
:parent_service_id => parent_service.id,
:parent_task_id => parent_service_task.id,
)
new_task.state = 'pending'
new_task.status = 'Ok'
new_task.source = child_svc_rsc.resource
new_task.save!
new_task.after_request_task_create
parent_service_task.miq_request.miq_request_tasks << new_task
tasks << new_task
end
end
tasks
end
def set_ownership(service, user)
return if user.nil?
service.evm_owner = user
if user.current_group
$log.info("Setting Service Owning User to Name=#{user.name}, ID=#{user.id}, Group to Name=#{user.current_group.name}, ID=#{user.current_group.id}")
service.miq_group = user.current_group
else
$log.info("Setting Service Owning User to Name=#{user.name}, ID=#{user.id}")
end
end
def self.default_provisioning_entry_point(service_type)
if service_type == 'atomic'
'/Service/Provisioning/StateMachines/ServiceProvision_Template/CatalogItemInitialization'
else
'/Service/Provisioning/StateMachines/ServiceProvision_Template/CatalogBundleInitialization'
end
end
def self.default_retirement_entry_point
'/Service/Retirement/StateMachines/ServiceRetirement/Default'
end
def self.default_reconfiguration_entry_point
nil
end
def template_valid?
validate_template[:valid]
end
alias template_valid template_valid?
def template_valid_error_message
validate_template[:message]
end
def validate_template
missing_resources = service_resources.select { |sr| sr.resource.nil? }
if missing_resources.present?
missing_list = missing_resources.collect { |sr| "#{sr.resource_type}:#{sr.resource_id}" }.join(", ")
return {:valid => false,
:message => "Missing Service Resource(s): #{missing_list}"}
end
service_resources.detect do |s|
r = s.resource
r.respond_to?(:template_valid?) && !r.template_valid?
end.try(:resource).try(:validate_template) || {:valid => true, :message => nil}
end
def provision_action
resource_actions.find_by(:action => "Provision")
end
def update_resource_actions(ae_endpoints)
resource_action_list.each do |action|
resource_params = ae_endpoints[action[:param_key]]
resource_action = resource_actions.find_by(:action => action[:name])
# If the action exists in updated parameters
if resource_params
# And the resource action exists on the template already, update it
if resource_action
resource_action.update!(resource_params.slice(*RESOURCE_ACTION_UPDATE_ATTRS))
# If the resource action does not exist, create it
else
build_resource_action(resource_params, action)
end
elsif resource_action
# If the endpoint does not exist in updated parameters, but exists on the template, delete it
resource_action.destroy
end
end
end
def create_resource_actions(ae_endpoints)
ae_endpoints ||= {}
resource_action_list.each do |action|
ae_endpoint = ae_endpoints[action[:param_key]]
next unless ae_endpoint
build_resource_action(ae_endpoint, action)
end
save!
end
def self.create_from_options(options)
create!(options.except(:config_info).merge(:options => { :config_info => options[:config_info] }))
end
private_class_method :create_from_options
def provision_request(user, options = nil, request_options = {})
request_options[:provision_workflow] = true
request_options[:parent_id] = options.delete('param_parent_request_id') unless options['param_parent_request_id'].nil?
result = order(user, options, request_options)
raise result[:errors].join(", ") if result[:errors].any?
result[:request]
end
def picture=(value)
if value.kind_of?(Hash)
super(Picture.new(value))
else
super
end
end
def queue_order(user_id, options, request_options)
MiqQueue.submit_job(
:class_name => self.class.name,
:instance_id => id,
:method_name => "order",
:args => [user_id, options, request_options],
)
end
def order(user_or_id, options = nil, request_options = {}, schedule_time = nil)
user = user_or_id.kind_of?(User) ? user_or_id : User.find(user_or_id)
workflow = provision_workflow(user, options, request_options)
if schedule_time
require 'time'
time = Time.parse(schedule_time).utc
errors = workflow.validate_dialog
errors << unsupported_reason(:order)
return {:errors => errors} if errors.compact.present?
schedule = MiqSchedule.create!(
:name => "Order #{self.class.name} #{id} at #{time}",
:description => "Order #{self.class.name} #{id} at #{time}",
:sched_action => {:args => [user.id, options, request_options], :method => "queue_order"},
:resource => self,
:run_at => {
:interval => {:unit => "once"},
:start_time => time,
:tz => "UTC",
},
)
{:schedule => schedule}
else
workflow.submit_request
end
end
def provision_workflow(user, dialog_options = nil, request_options = {})
dialog_options ||= {}
request_options.delete(:provision_workflow) if request_options[:submit_workflow]
ra_options = request_options.slice(:initiator, :init_defaults, :provision_workflow, :submit_workflow).merge(:target => self)
ResourceActionWorkflow.new(dialog_options, user, provision_action, ra_options).tap do |wf|
wf.request_options = request_options
end
end
def add_resource(rsc, options = {})
super
adjust_service_type
end
def self.display_name(number = 1)
n_('Service Catalog Item', 'Service Catalog Items', number)
end
def my_zone
# Catalog items can specify a zone to run in.
# Catalog bundle are used for grouping catalog items and are therefore treated as zone-agnostic.
zone&.name if atomic?
end
private
def update_service_resources(config_info, auth_user = nil)
config_info = config_info.except(:provision, :retirement, :reconfigure)
workflow_class = MiqProvisionWorkflow.class_for_source(config_info[:src_vm_id])
if workflow_class
service_resources.find_by(:resource_type => 'MiqRequest').try(:destroy)
new_request = workflow_class.new(config_info, auth_user).make_request(nil, config_info)
add_resource!(new_request)
end
end
def build_resource_action(ae_endpoint, action)
fqname = ae_endpoint[:fqname] || self.class.send(action[:method], *action[:args]) || ""
build_options = {:action => action[:name],
:fqname => fqname,
:ae_attributes => {:service_action => action[:name]}}
build_options.merge!(ae_endpoint.slice(*RESOURCE_ACTION_UPDATE_ATTRS))
resource_actions.build(build_options)
end
def validate_update_config_info(options)
if options[:service_type] && options[:service_type] != service_type
raise _('service_type cannot be changed')
end
if options[:prov_type] && options[:prov_type] != prov_type
raise _('prov_type cannot be changed')
end
options[:config_info]
end
def resource_action_list
[
{:name => ResourceAction::PROVISION,
:param_key => :provision,
:method => 'default_provisioning_entry_point',
:args => [service_type]},
{:name => ResourceAction::RECONFIGURE,
:param_key => :reconfigure,
:method => 'default_reconfiguration_entry_point',
:args => []},
{:name => ResourceAction::RETIREMENT,
:param_key => :retirement,
:method => 'default_retirement_entry_point',
:args => []}
]
end
def update_from_options(params)
options[:config_info] = params[:config_info]
update!(params.except(:config_info))
end
def construct_config_info
config_info = {}
miq_request_resource = service_resources.find_by(:resource_type => 'MiqRequest')
config_info.merge!(miq_request_resource.resource.options.compact) if miq_request_resource
config_info.merge!(resource_actions_info)
end
def resource_actions_info
resource_actions.each_with_object({}) do |resource_action, config_info|
resource_options = resource_action.slice(:dialog_id, :configuration_template_type, :configuration_template_id).compact
resource_options[:fqname] = resource_action.fqname
config_info[resource_action.action.downcase.to_sym] = resource_options.symbolize_keys
end
end
def generic_custom_buttons
CustomButton.buttons_for("Service")
end
def adjust_service_type
self.service_type = service_resources.any? { |st| st.resource_type.in?(['Service', 'ServiceTemplate']) } ? self.class::SERVICE_TYPE_COMPOSITE : self.class::SERVICE_TYPE_ATOMIC
end
end
scope :public_service_templates, -> {
joins(:miq_user_roles).where(miq_user_roles: { settings: nil })
}
Assuming the table exists. You need to join on that table in order to query it. Note, the default joins is an inner join that will remove records that don't have an associated miq_user_roles.
This will change the query substantially. If a record has_many miq_user_roles you'll likely need to add a distinct or distinct on clause. If it's possible to have no miq_user_roles, then records without them will now dissappear when you call the scope, since the inner join didn't find any.

How to make feed_entries downloaded every 3 minutes in mongoid

I have two models source.rb and feed_entries.rb. How to make feed_entries downloaded every 3 minutes.
I've tried through gem 'whenever' and received an error NoMethodError: private method `select'
source.rb
class Source
include Mongoid::Document
include Mongoid::Timestamps
field :url, type: String
field :title, type: String
field :site, type: String
after_save :load_feed_entries
has_many :feed_entries, dependent: :destroy
def load_feed_entries
last_entry = self.feed_entries.last
if last_entry.nil?
feed = Feedjira::Feed.fetch_and_parse(self.url)
else
feed = Feedjira::Feed.fetch_and_parse(self.url,
:if_modified_since => last_entry.published_at.to_time)
end
Source.add_entries(feed.entries, self.id)
end
def self.update_all_feeds(urls)
Feedjira::Feed.fetch_and_parse(urls,
:on_success => lambda { |url, feed|
rss = Source.select("sources.id").where(:url => url).first
Source.add_entries(feed.entries, rss.id)
}
)
end
private
def self.add_entries(entries, stream_id)
entries.each do |entry|
unless FeedEntry.where(guid: entry.id).exists?
FeedEntry.create!(
:name => entry.title,
:summary => entry.summary,
:url => entry.url,
:content => entry.content,
:published_at => entry.published,
:guid => entry.id,
:source_id => stream_id,
)
end
end
end
end
feed.rake
task :collect => :environment do
urls = Source.select("sources.url").all.map { |v| v[:url] }
Source.update_all_feeds(urls)
end
source.rb
def self.update_all_feeds(urls)
Feedjira::Feed.fetch_and_parse(urls,
:on_success => lambda { |url, feed|
rss = Source.only(:id).where(:url => url).first
Source.add_entries(feed.entries, rss.id)
}
)
end
feed.rake
task :collect => :environment do
urls = Source.only(:url).all.map { |v| v[:url] }
Source.update_all_feeds(urls)
end

Error "No Method" when using delayed job

I'm trying to import 90k lines of xml into my ruby app. herokus timeout limit is 30s so i'm trying to use delayed job.
The import class works wonderfully in around 48-hippopotomuses locally. When i add the line
handle_asynchronously :save_races
I get the error "undefined method save_races' for classXmltube'"
What am i doing wrong with DJ and how can i get this to work?
Full class code below
require "rexml/document"
class Xmltube
def self.convert_save(xml_data)
doc = REXML::Document.new xml_data.read
doc.elements.each("Meeting") do |meeting_element|
meeting = save_meeting(meeting_element)
save_races(meeting_element, meeting)
Rails.logger.info "all done"
end
end
def self.save_races(meeting_element, meeting)
meeting_element.elements.each("Races/Race") do |race_element|
race = save_race(race_element, meeting)
save_race_entrants(race_element, race)
end
end
def self.save_race_entrants(race_element, race)
race_element.elements.each("RaceEntries/RaceEntry") do |entry_element|
horse = save_horse(entry_element)
jockey = save_jockey(entry_element)
start = save_start(entry_element, horse, jockey, race)
save_sumaries(entry_element, start)
end
end
def self.save_track(meeting_element)
# there is only one track, but still, each? wtf.
t = {}
meeting_element.elements.each("Track") do |track|
t = {
:name => track.attributes["VenueName"],
:track_code => track.attributes["VenueCode"],
:condition => track.elements['TrackRating'].text,
:club_id => save_club(meeting_element.elements["Club"]).id
}
end
track = Track.where(:track_code => t[:track_code] ).first
if track
Track.update(track.id, t)
else
Track.create(t)
end
end
def self.save_meeting meeting_element
t = {
:meet_code => meeting_element.attributes['MeetCode'],
:stage => meeting_element.elements["MeetingStage"].text,
:phase => meeting_element.elements["MeetingPhase"].text,
:nominations_close_at => meeting_element.elements["NominationsClose"].text,
:acceptance_close_at => meeting_element.elements["AcceptanceClose"].text,
:riders_close_at => meeting_element.elements["RidersClose"].text,
:weights_published_at => meeting_element.elements["WeightsPublishing"].text,
:club_id => save_club(meeting_element.elements["Club"]).id ,
:track_id => save_track(meeting_element).id,
:tab_status => meeting_element.elements["TabStatus"].text,
:state => meeting_element.elements["StateDesc"].text,
:day_night => meeting_element.elements["DayNight"].text,
:number_of_races => meeting_element.elements["NumOfRaces"].text,
:meet_date => meeting_element.elements["MeetDate"].text,
}
meeting = Meeting.where(:meet_code => t[:meet_code] ).first
if meeting
Meeting.update(meeting.id, t)
else
Meeting.create(t)
end
end
############################################################
def self.save_sumaries entry_element, start
entry_element.elements.each('Form/ResultsSummaries/ResultsSummary') do | element |
s = {
:name => element.attributes['Name'],
:start_id => start.id,
:starts => element.attributes['Starts'],
:wins => element.attributes['Wins'],
:seconds => element.attributes['Seconds'],
:thirds => element.attributes['Thirds'],
:prize_money => element.attributes['PrizeMoney'],
}
sum = Summary.where(:name => s[:name] ).where(:start_id => s[:start_id]).first
if sum
Summary.update(sum.id, s)
else
Summary.create(s)
end
end
end
def self.save_start entry_element, horse, jockey, race
s = {
:horse_id => horse.id,
:jockey_id => jockey.id,
:race_id => race.id,
:silk => entry_element.elements["JockeySilksImage"].attributes["FileName_NoExt"],
:start_code => entry_element.attributes['RaceEntryCode'],
:handicap_weight => entry_element.elements['HandicapWeight'].text,
}
# Rails.logger.info entry_element['HandicapWeight'].text
start = Start.where(:start_code => s[:start_code] ).first
if start
Start.update(start.id, s)
else
Start.create(s)
end
end
def self.save_jockey entry_element
j={
:name => entry_element.elements['JockeyRaceEntry/Name'].text,
:jockey_code => entry_element.elements['JockeyRaceEntry'].attributes["JockeyCode"],
}
jockey = Jockey.where(:jockey_code => j[:jockey_code] ).first
if jockey
Jockey.update(jockey.id, j)
else
Jockey.create(j)
end
end
def self.save_horse entry_element
trainer = save_trainer entry_element
h= {
:name => entry_element.elements['Horse'].attributes["HorseName"],
:color => entry_element.elements['Horse'].attributes["Colour"],
:dob => entry_element.elements['Horse'].attributes["FoalDate"],
:sex => entry_element.elements['Horse'].attributes["Sex"],
:trainer_id => trainer.id,
:horse_code => entry_element.elements['Horse'].attributes["HorseCode"],
}
horse = Horse.where(:horse_code => h[:horse_code] ).first
if horse
Horse.update(horse.id, h)
else
Horse.create(h)
end
end
def self.save_trainer entry_element
t= {
:name => entry_element.elements['Trainer/Name'].text,
:trainer_code => entry_element.elements['Trainer'].attributes["TrainerCode"]
}
trainer = Trainer.where(:trainer_code => t[:trainer_code] ).first
if trainer
Trainer.update(trainer.id, t)
else
Trainer.create(t)
end
end
def self.save_club element
t = {}
t = {
:club_code => element.attributes['ClubCode'],
:title => element.attributes["Title"],
}
club = Club.where(:club_code => t[:club_code] ).first
if club
Club.update(club.id, t)
else
Club.create(t)
end
end
def self.save_race element, meeting
r = {
:name => element.elements['NameRaceFull'].text,
:occur => element.elements['RaceStartTime'].attributes["TimeAtVenue"],
:distance => element.elements['RaceDistance'].text,
:race_type => element.elements['RaceType'].text,
:track_id => meeting.track_id,
:race_code => element.attributes["RaceCode"],
:meeting_id => meeting.id
}
race = Race.where(:race_code => r[:race_code] ).first
if race
Race.update(race.id, r)
else
Race.create(r)
end
end
handle_asynchronously :save_races
end
Since your save_races is a class method, you should call handle_asynchronously on Xmltube's singleton class:
class << self
handle_asynchronously :save_races
end
This just worked as I would expect
class Foo
def self.bar(s)
Rails.logger.info "From Foo.bar('#{s}')"
end
end
# then ...
Foo.delay.bar('hello')
I was running 4.0.4 of DJ with ruby 2.1

Ruby on Rails: Is it right how I coded my Category-Tree (Is it ruby-like?)

I am new to Rails and just got my category tree working. Now I am not sure if what I have done is "ruby conform" or "ruby-like". I come from PHP and have to change some of my habits but this is not easy. I just want to check if I am on the right way.
The structure is done by the scaffold-command so I guess its correct.
So obvisoulythere is a model-class which is called Category and inherits from ActiveRecord::Base. This model has the following attributes/database fields:
*id,media,image,small_image,clicks,parent,active,description,name,created_at,updated_at*
This is the content of my model-class:
class Category < ActiveRecord::Base
has_many :articles,
:foreign_key => 'category'
belongs_to :parent_object,
:foreign_key => "parent",
:class_name => "Category"
has_many :children,
:foreign_key => "parent",
:class_name => "Category",
:order => "name ASC",
:dependent => :delete_all
#tree = Hash.new
#treepart = Hash.new
def self.category_tree
#root_categories = self.find(:all, :conditions => ["parent = ?", 0])
if #root_categories.length >= 1
#root_categories.each do |level|
#tree[level.id] = level.child_loop(level)
end
#tree
end
end
def child_loop(child)
#treepart = { :category => child }
#treepart[:children] = Hash.new
child.children.each do |child|
#treepart[:children][child.id] = child.child_loop(child)
end
#treepart
end
end
Categories can be nested therefore I have integrated a self-relating belongs_to and has_many function. I have called the parent *:parent_object* because only :parent does not work. Maybe it is in conflict with the attribute-name.
In the model I collect all categories with the method *category_tree* and *child_loop*. After this call I get an image of the category-tree in form of a hash.
Category.category_tree
I do this directly in the Articles´ *_form.html.erb* and pass it to my helper which is generating the html. Here is the call from the from-template:
<%= build_category_tree(Category.category_tree).html_safe %>
The helper is rendering as follows:
module CategoriesHelper
def build_category_tree(object_tree)
tree = object_tree
#treestring = "<ul>" + self.level_loop(tree) + "</ul>"
end
def level_loop(level)
#levelstring = ''
if !level.nil?
level.each do |id,item|
if item.has_key?(:category) && !item.nil?
#levelstring += "<li>" + item[:category].name + "</li>"
#levelstring += "<ul>" + self.level_loop(item[:children]) + "</ul>"
end
end
end
# in the end, return string to prevent a nil return
#levelstring += ""
end
end
Is this the ruby-way to code, can I shorten or change something completely?
Thanks for your help

How to get attribue in the to_json attribute

I am using Rails 3 and here is my model
class LineItem < ActiveRecord::Base
attr_reader :price
belongs_to :product
def price
self.product.price * self.quantity
end
def as_json(options = {})
super(:include => [:product])
end
end
Above code works. However now I want my json to also have value for price in addition to the other values that I am getting.
How do I accomplish that?
You can use :methods:
def as_json(options = {})
super(options.merge(:include => [:product], :methods => [:price]))
end
You might want to pay proper attention to any incoming :include and :method settings in your options though. So you might want to use the block form of merge:
EXTRAS = { :include => [:product], :methods => [:price] }
def as_json(options = { })
super(options.merge(EXTRAS) { |k,ov,nv| ov.is_a?(Array) ? ov + nv : nv }
end

Resources