rails 3: hash attribute in a override to_xml model method - ruby-on-rails

I wrote a override for the to_xml model method and right now im trying to get a hash attribute to be transformed into a set if symbol => values pair but i had no success.
the result of the intersected_categories method is a hash like:
{:"1"=>["Broken Board", false], :"2"=>["Sticking", false], :"3"=>["Bottom tier missing", false], :"4"=>["Bad I/L", false], :"5"=>["Delamination", false], :"7"=>["Sheet level - smile", false], :"8"=>["Sheet level - frown", false], :"9"=>["Missing SS", false]}
The to_xml method
def to_xml (options={})
xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
xml.instruct! unless options[:skip_instruct]
xml.wip #wip,
:number => self.number,
:start_time => self.wip_start_time,
:end_time => self.wip_end_time,
:line => self.system.name,
:shift => self.shift,
:crew => self.crewF,
:sm_crew => self.crewSM,
:sm_shift => self.shiftSM,
:product => self.SMMainGroup,
:product_group => self.product_group,
:sheets => self.sheets,
:interleavers => self.interleavers,
:wip_grade => self.intersected_categories,
:comment => self.comment
end
ive tried a couple of things with no success:
def to_xml (options={})
xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
xml.instruct! unless options[:skip_instruct]
#wip.intersected_categories.each do |grade|
wip_categories << {grade[1][0].to_sym => grade[0][1]}
end
.
.
:comment => self.comment,
wip_categories #explodes
end
###### another try
:interleavers => self.interleavers,
:wip_grade => self.intersected_categories,
:comment => self.comment,
self.intersected_categories.each do |grade|
<< grade[1][0].to_sym => grade[0][1] #with / without {} it keeps failing
end
end
Any idea how can i achieve what i need?
Update
Current xml:
<wip number="123h11008" start_time="2014-05-13 09:21:00 -0500" end_time="" line="cl1" shift="1" crew="A" sm_crew="A" sm_shift="1" product="1111111" product_group="G2" sheets="0" interleavers="0" wip_grade="{:"2"=>["Bottom Tier Missing", false], :"3"=>["Falling", false], :"4"=>["Broken Boards", false], :"5"=>["Crown", false], :"6"=>["DIP", false], :"7"=>["Green Boards", false], :"8"=>["Delamination", false], :"9"=>["Bad I/L", false]}" comment=""/>
expected xml:
<wip number="123h11008" start_time="2014-05-13 09:21:00 -0500" end_time="" line="cl1" shift="1" crew="A" sm_crew="A" sm_shift="1" product="1111111" product_group="G2" sheets="0" interleavers="0" Bottom Tier Missing=false Falling = false Broken Boards = false Crown = false DIP = false Green Boards = false Delamination = false Bad I/L = false comment=""/>

Try:
xml.wip #wip, {
:number => self.number,
:start_time => self.wip_start_time,
:end_time => self.wip_end_time,
:line => self.system.name,
:shift => self.shift,
:crew => self.crewF,
:sm_crew => self.crewSM,
:sm_shift => self.shiftSM,
:product => self.SMMainGroup,
:product_group => self.product_group,
:sheets => self.sheets,
:interleavers => self.interleavers,
:comment => self.comment }.merge(Hash(self.intersected_categories.values))

Related

TypeError no implicit conversion of Symbol into Integer

Hash
data = {
:recordset => {
:row => {
:property => [
{:name => "Code", :value => "C0001"},
{:name => "Customer", :value => "ROSSI MARIO"}
]
}
},
:#xmlns => "http://localhost/test"
}
Code Used
result = data[:recordset][:row].each_with_object([]) do |hash, out|
out << hash[:property].each_with_object({}) do |h, o|
o[h[:name]] = h[:value]
end
end
I cannot get the following output:
[{"Code"=>"C0001", "Customer"=>"ROSSI MARIO", "Phone1"=>"1234567890"}
Error message:
TypeError no implicit conversion of Symbol into Integer
It works correctly in case of multi records
data = {
:recordset => {
:row => [{
:property => [
{:name => "Code", :value => "C0001"},
{:name => "Customer", :value => "ROSSI MARIO"},
{:name => "Phone1", :value => "1234567890"}
]
}, {
:property => [
{:name => "Code", :value => "C0002"},
{:name => "Customer", :value => "VERDE VINCENT"},
{:name => "Phone1", :value => "9876543210"},
{:name => "Phone2", :value => "2468101214"}
]
}]
},
:#xmlns => "http://localhost/test"
}
Code used
data.keys
#=> [:recordset, :#xmlns]
data[:recordset][:row].count
#=> 2 # There are 2 set of attribute-value pairs
result = data[:recordset][:row].each_with_object([]) do |hash, out|
out << hash[:property].each_with_object({}) do |h, o|
o[h[:name]] = h[:value]
end
end
#=> [
# {"Code"=>"C0001", "Customer"=>"ROSSI MARIO", "Phone1"=>"1234567890"},
# {"Code"=>"C0002", "Customer"=>"VERDE VINCENT", "Phone1"=>"9876543210", "Phone2"=>"2468101214"}
# ]
In the first case data[:recordset][:row] is not an Array, it's a Hash, so when you iterate it, the hash variable becomes the array:
[:property, [{:name=>"Code", :value=>"C0001"}, {:name=>"Customer", :value=>"ROSSI MARIO"}]]
In the second case, it's an Array, not a Hash, so when you iterate it, it becomes the hash:
{:property=>[{:name=>"Code", :value=>"C0001"}, {:name=>"Customer", :value=>"ROSSI MARIO"}, {:name=>"Phone1", :value=>"1234567890"}]}
You're always assuming it's the second format. You could force it into an array, and then flatten by 1 level to treat both instances the same:
result = [data[:recordset][:row]].flatten(1).each_with_object([]) do |hash, out|
out << hash[:property].each_with_object({}) do |h, o|
o[h[:name]] = h[:value]
end
end
# => [{"Code"=>"C0001", "Customer"=>"ROSSI MARIO"}] # result from example 1
# => [{"Code"=>"C0001", "Customer"=>"ROSSI MARIO", "Phone1"=>"1234567890"},
# {"Code"=>"C0002", "Customer"=>"VERDE VINCENT",
# "Phone1"=>"9876543210", "Phone2"=>"2468101214"}] # result from example 2
It's tempting to try and use Kernal#Array() instead of [].flatten(1), but you have to remember that Hash implements to_a to return a nested array of keys and values, so Kernal#Array() doesn't work like you'd want it to:
Array(data[:recordset][:row]) # using the first example data
# => [[:property, [{:name=>"Code", :value=>"C0001"}, {:name=>"Customer", :value=>"ROSSI MARIO"}]]]
You can create an array if it's not an array to normalize the input before processing it.
info = data[:recordset][:row]
info = [info] unless info.is_an? Array
result = info.each_with_object([]) do ....

Rails smart_listing configuration

I'm trying to setup the smart_listing gem in my app. Where and how can I configure the default per page number of pagination results. In the docs of smart_listing is mentioned that it uses kaminari.
If you don't already have a config/initializers/kaminari_config.rb file, run Kaminari's config generator:
bundle exec rails generate kaminari:config
This will create config/initializers/kaminari_config.rb with the default content:
Kaminari.configure do |config|
# config.default_per_page = 25
# config.max_per_page = nil
# config.window = 4
# config.outer_window = 0
# config.left = 0
# config.right = 0
# config.page_method_name = :page
# config.param_name = :page
end
Simply uncomment and edit the configuration options you are interested in changing.
Update:
SmartListing provides it's own configuration options for pagination in config/initializers/smart_listing.rb:
SmartListing.configure do |config|
config.global_options({
#:param_names => { # param names
#:page => :page,
#:per_page => :per_page,
#:sort => :sort,
#},
#:array => false, # controls whether smart list should be using arrays or AR collections
#:max_count => nil, # limit number of rows
#:unlimited_per_page => false, # allow infinite page size
#:paginate => true, # allow pagination
#:memorize_per_page => false, # save per page settings in the cookie
#:page_sizes => DEFAULT_PAGE_SIZES, # set available page sizes array
#:kaminari_options => {:theme => "smart_listing"}, # Kaminari's paginate helper options
})
config.constants :classes, {
#:main => "smart-listing",
#:editable => "editable",
#:content => "content",
#:loading => "loading",
#:status => "smart-listing-status",
#:item_actions => "actions",
#:new_item_placeholder => "new-item-placeholder",
#:new_item_action => "new-item-action",
#:new_item_button => "btn",
#:hidden => "hidden",
#:autoselect => "autoselect",
#:callback => "callback",
#:pagination_per_page => "pagination-per-page text-center",
#:pagination_count => "count",
#:inline_editing => "info",
#:no_records => "no-records",
#:limit => "smart-listing-limit",
#:limit_alert => "smart-listing-limit-alert",
#:controls => "smart-listing-controls",
#:controls_reset => "reset",
#:filtering => "filter",
#:filtering_search => "glyphicon-search",
#:filtering_cancel => "glyphicon-remove",
#:filtering_disabled => "disabled",
#:sortable => "sortable",
#:icon_new => "glyphicon glyphicon-plus",
#:icon_edit => "glyphicon glyphicon-pencil",
#:icon_trash => "glyphicon glyphicon-trash",
#:icon_inactive => "glyphicon glyphicon-circle",
#:icon_show => "glyphicon glyphicon-share-alt",
#:icon_sort_none => "glyphicon glyphicon-resize-vertical",
#:icon_sort_up => "glyphicon glyphicon-chevron-up",
#:icon_sort_down => "glyphicon glyphicon-chevron-down",
}
config.constants :data_attributes, {
#:main => "smart-listing",
#:confirmation => "confirmation",
#:id => "id",
#:href => "href",
#:callback_href => "callback-href",
#:max_count => "max-count",
#:inline_edit_backup => "smart-listing-edit-backup",
#:params => "params",
#:observed => "observed",
#:href => "href",
#:autoshow => "autoshow",
#:popover => "slpopover",
}
config.constants :selectors, {
#:item_action_destroy => "a.destroy",
#:edit_cancel => "button.cancel",
#:row => "tr",
#:head => "thead",
#:filtering_icon => "i"
}
end
Uncomment the page_sizes line and replace DEFAULT_PAGE_SIZES with an array like [10, 20, 50, 100]
No need to comment out page_sizes in initializers/smart_listing.rb.
You can just define per_page value in controller, eg:
users_scope = User.all.includes(:bio)
users_scope = users_scope.like(params[:filter]) if params[:filter]
#users = smart_listing_create :users, users_scope, partial: "users/list", page_sizes: [5, 7, 13, 26]
smart_listing v1.1.2

Ruby On Rails Mail Routine Not sending

I Have a ROR IF statement that is supposed to look up a record and then send emails based on the login can anyone tell me what is wrong in the syntax?
this is now working but there is two test cases that return ActiveRecord::RecordNotFound (Couldn't find SignOn with userw1 = xxx#example.com):
app/models/order.rb:219:in `submit_order'
class Order < ActiveRecord::Base
# NOTE: ensure that you always setup methods here to include and filter on
# query_account_number as a security measure.
establish_connection "web_#{RAILS_ENV}"
has_many :order_details, :dependent => :destroy, :order => 'id DESC'
def self.delete_item query_account_number, login, id
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
detail = order.order_details.first(:conditions => {:id => id})
detail.destroy if detail
# Here we would delete the order, but have chosen to leave it so they do not have
# questionable gaps in IDs.
end
def self.verify_upc1 upc_rule, upc1
"Invalid UPC Prefix" unless Item.first(:conditions => ["rul31c = ? AND CONCAT(TRIM(comi1c), 'A') = ?", upc_rule, upc1 + "A"],
:select => "style")
end
def self.verify_upc2 upc_rule, upc1, upc2
"Invalid UPC Prefix or Subnumber" unless Item.first(:conditions => ["rul31c = ? AND CONCAT(TRIM(comi1c), CONCAT(TRIM(arsb1c), 'A')) = ?", upc_rule, upc1 + upc2 + "A"],
:select => "style")
end
def self.verify_style upc_rule, style
"Invalid Style" unless Item.first(:conditions => ["rul31c = ? AND CONCAT(TRIM(style), 'A') = ?", upc_rule, style + "A"],
:select => "style")
end
def self.update_quantity query_account_number, login, id, quantity
if quantity.to_i > 0
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
detail = order.order_details.first(:conditions => {:id => id})
if detail
detail.quantity = quantity.to_i
detail.save
end
end
end
def self.update_order_note query_account_number, login, order_note
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
order.note = order_note
order.save
end
def self.update_order_item_note query_account_number, login, id, note
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
detail = order.order_details.first(:conditions => {:id => id})
if detail
detail.note = note
detail.save
end
end
def self.add_item query_account_number, login, quantity, upc1, upc2, price_code, upc_rule
if quantity.to_i > 0
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
order = Order.add_order_header(query_account_number, login) if order.blank?
if order
item = Item.first(:conditions => ["rul31c = ? AND CONCAT(TRIM(comi1c), CONCAT(TRIM(arsb1c), 'A')) = ?", upc_rule, upc1 + upc2 + "A"],
:select => "style, color, size, pnum35, cono35, comi1c, arsb1c, ptyp35")
price = Price.first(:conditions => {:catnwp => item.pnum35, :conowp => item.cono35, :listwp => price_code}, :select => "prcewp") unless item.blank?
if item and price
order_detail = OrderDetail.new(:style => item.style,
:order_id => order.id,
:quantity => quantity,
:color => item.color,
:size => item.size)
order_detail.save
# Return a cart item hash
cart_contents = []
cart_contents << {:style => item.style,
:color => item.color,
:size => item.size,
:quantity => quantity,
:name => ProItem.short_description(item.style),
:price => price.prcewp,
:type => item.ptyp35,
:upc => item.comi1c + item.arsb1c,
:id => order_detail.id}
end
end
end
end
def self.order_info_update query_account_number, login, info
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
if order
if info.has_key?("name")
order.name = info[:name]
order.address1 = info[:address1]
order.address2 = info[:address2]
order.address3 = info[:address3]
order.city = info[:city]
order.state = info[:state]
order.zip = info[:zip]
end
if info.has_key?("po_number")
order.po_number = info[:po_number]
end
order.save
# where does po number go???
end
end
def self.mailing_address query_account_number, login
o = Order.first(:conditions => {:account_number => query_account_number, :login => login})
{:name => o.name, :address1 => o.address1, :address2 => o.address2, :address3 => o.address3, :city => o.city, :state => o.state, :zip => o.zip} if o
end
def self.order_note query_account_number, login
o = Order.first(:conditions => {:account_number => query_account_number, :login => login}, :select => "note")
o.note if o
end
def self.cart_contents query_account_number, login, price_code, upc_rule
# TODO: what to do if item changed since they put it in cart?
# Perhaps we expire a cart after a while, but, that still is not a perfect solution.
# Ideally here we go through each style, make sure it is still valid for the customer, and
# check color/size as well.
order_items = Order.first(:conditions => {:account_number => query_account_number, :login => login} )
if order_items
cart_contents = []
order_items.order_details.each do |oi|
as400_item = Item.first(:conditions => {:rul31c => upc_rule, :style => oi.style.ljust(9), :color => oi.color, :size => oi.size },
:select => "pnum35, cono35, ptyp35, comi1c, arsb1c")
price = Price.first(:conditions => {:catnwp => as400_item.pnum35, :conowp => as400_item.cono35, :listwp => price_code}, :select => "prcewp") unless as400_item.blank?
cart_contents << {:style => oi.style,
:color => oi.color,
:size => oi.size,
:quantity => oi.quantity,
:name => ProItem.short_description(oi.style),
:price => price.prcewp,
:type => as400_item.ptyp35,
:note => oi.note,
:upc => as400_item.comi1c + as400_item.arsb1c,
:id => oi.id} if as400_item and price
end unless order_items.blank?
cart_contents
end
end
def self.cart_contents_count query_account_number, login
order_items = Order.first(:conditions => {:account_number => query_account_number, :login => login} )
count = 0
order_items.order_details.each {|oi| count += oi.quantity } if order_items
count
end
def self.cart_contents_total query_account_number, login, price_code, upc_rule
order_items = Order.first(:conditions => {:account_number => query_account_number, :login => login} )
total = 0
order_items.order_details.each do |oi|
as400_item = Item.first(:conditions => {:rul31c => upc_rule, :style => oi.style.ljust(9), :color => oi.color, :size => oi.size },
:select => "pnum35, cono35, ptyp35")
price = 0
if !as400_item.blank?
price = Price.first(:conditions => {:catnwp => as400_item.pnum35, :conowp => as400_item.cono35, :listwp => price_code}, :select => "prcewp")
total += (oi.quantity * price.prcewp.to_f)
end
end if order_items
total
end
def self.add_order_details query_account_number, login, items, notes = Hash.new
result = false
if items
# If there is not an order record, create one. Basically we only
# allow one open order per login at a time, and if there is
# one already, we continue to append order_detail records to it.
order = Order.first(:conditions => {:account_number => query_account_number, :login => login.upcase})
order = Order.add_order_header(query_account_number, login) if order.blank?
items.each do |key, value|
if value.to_i > 0
result = true
style = key[0..8]
color = key[9..11]
size = key[12..14]
order_detail = OrderDetail.new(:style => style,
:order_id => order.id,
:quantity => value,
:color => color,
:size => size,
:note => (notes ? notes[key] : ''))
order_detail.save
end
end if order
end
result
end
def self.submit_order query_account_number, login, price_code, distributor_number
o = Order.first(:conditions => {:account_number => query_account_number, :login => login})
# TODO: transaction or some error handling
if o
# Find all associated records we need.
customer = Customer.first(:conditions => {:cusn05 => query_account_number}, :select => "cono05, cgp405, slmn05, list20" )
sign_on = SignOn.first(:conditions => {:userw1 => login.upcase},
:select => "idnow1, bsnamw1, accntw1, prfdstw1, cntacw1, bsadd1w1, bsadd2w1, bsadd3w1, bscityw1, bsstcdw1, bszipw1, acctypw1")
distributor = Distributor.first(:conditions => {:cusnp1 => distributor_number}, :select => "cnam05, emailp1")
if sign_on.acctypw1.strip == "DS"
rec = SignOn.find_by_userw1!(login)
webid = rec.prfdstw1
elsif sign_on.acctypw1.strip == "DSD"
rec = SignOn.find_by_userw1!(login)
webid = rec.prfdstw1
end
#cnt = Weboel23.count(:all,:conditions => {:act223 => mp})
weboel23 = Weboel23.first(:conditions => {:act223 => webid}, :select => "emal23")
#cnt=weboel23.count
approval0=Weboel23.get_email_by_account0(webid)
approval1=Weboel23.get_email_by_account1(webid)
approval2=Weboel23.get_email_by_account2(webid)
approval3=Weboel23.get_email_by_account3(webid)
approval4=Weboel23.get_email_by_account4(webid)
# weboel23 = Weboel23.each(:conditions => {:act223 => mp}, :select => "emal23")
#approval = weboel23.emal23
#f=File.open("/var/www/onlineordering.coastalpet.com/log/debug3.txt")
#establish_connection "as400_#{RAILS_ENV}"
#f.puts "prfdstw1"
#f.puts rec = SignOn.find_by_userw1!(login)
#f.puts "type="+elephant
#f.puts "email="+approval0
#f.close
# s = find_by_sql ["SELECT EMAL23 emal23 FROM WEBOEL23 WHERE ACT223 = ?", distributor_number]
# d << { :id => s[0].emal23 } unless s.blank?
if customer and sign_on
as400_order_id = "WB" + o.id.to_s.rjust(8, "0")
total = 0
count = 0
line = 1 # Start at 1 per Ron Hoopes 2/14/2011
o.order_details.each do |oi|
item = Item.first(:conditions => {:rul31c => customer.cgp405, :style => oi.style.ljust(9), :color => oi.color, :size => oi.size },
:select => "comi1c, arsb1c, chdt1c, pnum35, cono35, pdes35")
price = Price.first(:conditions => {:catnwp => item.pnum35, :conowp => item.cono35, :listwp => price_code}, :select => "prcewp") unless item.blank?
if item and price
WebOrderDetail.create(:conowd => customer.cono05,
:uniqwd => as400_order_id,
:linewd => line,
:itemwd => oi.style.ljust(9) + oi.color + oi.size,
:barcwd => item.comi1c.strip + item.arsb1c.strip + item.chdt1c.strip,
:altiwd => "",
:itmdwd => item.pdes35,
:qtywd => oi.quantity,
:uprcwd => price.prcewp.to_f.round_to(2),
:listwd => customer.list20,
:dtdrwd => "0",
:dcd1wd => "",
:dsc1wd => "0",
:dcd2wd => "",
:dsc2wd => "0")
# Create any order ITEM notes.
unless oi.note.blank?
oi.note.scan(/.{1,70}/).each_with_index do |note, index|
WebOrderNote.create(:conown => customer.cono05,
:textwn => note,
:uniqwn => as400_order_id,
:linewn => line,
:seqwn => index)
end
end
count += oi.quantity.to_i
total += oi.quantity.to_i * price.prcewp.to_f.round_to(2)
line += 1
end
end
# Create any order notes.
unless o.note.blank?
o.note.scan(/.{1,70}/).each_with_index do |note, index|
WebOrderNote.create(:conown => customer.cono05,
:textwn => note,
:uniqwn => as400_order_id,
:linewn => 0,
:seqwn => index)
end
end
# Coastal's definition a current century is off by one, hence the math for the date.
as400_order_header = WebOrder.new(:conowc => customer.cono05,
:uniqwc => as400_order_id,
:idnowc => sign_on.idnow1,
:namewc => o.name,
:addr1wc => o.address1,
:addr2wc => o.address2,
:addr3wc => o.address3,
:citywc => o.city,
:statewc => o.state,
:zipcdwc => o.zip,
:cusnwc => query_account_number,
:dtordwc => Utilities.to_db2_date(Date.today),
:shpdtwc => Utilities.to_db2_date(Date.today),
:cusowc => o.po_number.blank? ? as400_order_id : o.po_number,
:slmnwc => customer.slmn05,
:rulewc => customer.cgp405,
:listwc => customer.list20,
:valuewc => total.to_f.round_to(2),
:statwc => "")
if as400_order_header.save
# Sent confirmation email, if required. Only send it for users that chose a distributor,
# whether they had to choose one or not. We determine this by looking at the account number
# in the sign_on and comparing it with the order number we are using for the order. If
# that is different, it indicates that they chose a distributor.
# These are used in the email body, key for the hash is the replacement tags, capitalized, &
# prepended and appended with '##', e.g. ##NAME## - and any underlines are replaced with space
email_details = {"name" => sign_on.bsnamw1,
"order_number" => as400_order_id,
"order_total" => format('$%.2f', total),
"order_count" => count.to_s,
"order_date" => Date.today.to_s,
"distributor_name" => (distributor ? distributor.cnam05 : ""),
"distributor_contact" => "UNKNOWN",
"customer_name" => sign_on.bsnamw1,
"customer_address" => sign_on.bsadd1w1.strip + (!sign_on.bsadd2w1.blank? ? "<br>" + sign_on.bsadd2w1.strip : "") + (!sign_on.bsadd3w1.blank? ? "<br>" + sign_on.bsadd3w1.strip : ""),
"customer_city" => sign_on.bscityw1,
"customer_state" => sign_on.bsstcdw1,
"customer_zip" => sign_on.bszipw1,
"customer_contact" => sign_on.cntacw1}
Mailer.deliver_order_coastal_notify_email("Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
# Per Dana 6/30/2012, JUST DS
if sign_on.acctypw1.strip == "DS" or sign_on.acctypw1.strip == "DSD"
# If there is no distributor email address, the mailer model will substitute in the admin's email from their settings
Mailer.deliver_order_distributor_approval_email(distributor ? distributor.emailp1 : "", "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation #{approval0} #{approval1}", email_details)
if approval0!=""
Mailer.deliver_order_confirmation_email(login, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
Mailer.deliver_order_distributor_approval_email(approval0, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation ", email_details)
Mailer.deliver_order_coastal_notify_email("Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
end
if approval1!=""
Mailer.deliver_order_confirmation_email(login, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
Mailer.deliver_order_distributor_approval_email(approval1, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation ", email_details)
Mailer.deliver_order_coastal_notify_email("Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
end
if approval2!=""
Mailer.deliver_order_confirmation_email(login, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
Mailer.deliver_order_distributor_approval_email(approval2, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation ", email_details)
Mailer.deliver_order_coastal_notify_email("Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
end
if approval3!=""
Mailer.deliver_order_confirmation_email(login, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
Mailer.deliver_order_distributor_approval_email(approval3, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation ", email_details)
Mailer.deliver_order_coastal_notify_email("Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
end
if approval4!=""
Mailer.deliver_order_confirmation_email(login, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
Mailer.deliver_order_distributor_approval_email(approval4, "Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation ", email_details)
Mailer.deliver_order_coastal_notify_email("Coastal Pet Online Ordering<noreply#coastalpet.com>", "Order Confirmation", email_details)
end
Mailer.deliver_order_distributor_approval_email(weboel23 ? weboel23.emal23: "", "Coastal Pet Online Ordering<noreply#coastalpet.com>", "*Order Confirmation", email_details)
Mailer.deliver_order_distributor_approval_email("robert.kendall#coastalpet.com", "Coastal Pet Online Ordering<noreply#coastalpet.com>", "*Order Confirmation", email_details)
end
# Al ways notify Coastal staff
# Update the last ordered date (used for reminders)
User.update_last_order_date(login)
o.destroy
as400_order_id
end
end
end
end
def self.count_user_orders query_account_number, login
count = Order.first(:conditions => {:account_number => query_account_number, :login => login})
count.order_details.count unless count.blank? or count == 0
end
def self.reorder(order_number, login, query_account_number, upc_rule, price_code, mode)
warnings = ""
# If we are not in check mode, then blank out cart
self.empty_cart(query_account_number, login) if mode != "check"
# Get the previous order
oo = WebOrder.get_previous_order(order_number, login)
# Go through each line item
oo.each do |ooi|
# Verify it still exists in the AS400 and is same price
# Note that this reports back a -1 if it cannot find the
# same style+color+size option, otherwise just reports
# price if it finds it.
current_price = Item.check_item_exists(query_account_number, ooi[:style], ooi[:color], ooi[:size], upc_rule, price_code)
# If item was not found, we can't add it.
# We could spend more time to determine if it was the color, or size, or that
# the style itself is not available, but it seems reasonable enough to
# present it this way. Really should not be doing this "presentation" in
# the model, but we don't have views setup for Ajax so we have to give the
# controller the text we want rendered.
if current_price == -1
warnings += "SKU "+ ooi[:style].to_s + ooi[:color].to_s + ooi[:size].to_s + " is no longer available<br />"
else
# If price did not match, append to list of warnings
if current_price.to_f.round_to(2) != ooi[:price].to_f.round_to(2)
warnings += "SKU "+ ooi[:style].to_s + ooi[:color].to_s + ooi[:size].to_s + " price is " +
ActionController::Base.helpers.number_to_currency(current_price) + " and it was " +
ActionController::Base.helpers.number_to_currency(ooi[:price]) + "<br />"
end
# If not in check mode, add item to cart
# In this case, we don't care that the price did
# not match, we still add it.
populate_cart(query_account_number, login, ooi[:style], ooi[:color], ooi[:size], ooi[:quantity], ooi[:line_item_note], ooi[:order_note]) if mode != "check"
end
end
mode == "check" ? warnings : ""
end
def self.empty_cart query_account_number, login
order = Order.first(:conditions => {:account_number => query_account_number, :login => login})
order.destroy if order
end
def self.populate_cart query_account_number, login, style, color, size, quantity, note, order_note
# If there is not an order record, create one. Basically we only
# allow one open order per login at a time, and if there is
# one already, we continue to append order_detail records to it.
order = Order.first(:conditions => {:account_number => query_account_number, :login => login.upcase})
order = Order.add_order_header(query_account_number, login) if order.blank?
# These can be null for kits, and we don't like nulls in the database for this
color = "" if color.blank?
size = "" if size.blank?
if order
order.note = order_note # yeah we do this each time but while inefficient it works
order.save
order_detail = OrderDetail.new(:style => style,
:order_id => order.id,
:quantity => quantity,
:color => color,
:size => size,
:note => note)
order_detail.save
end
end
private
def self.add_order_header query_account_number, login
# Default address info to sign_on
sign_on = SignOn.first(:conditions => {:userw1 => login.upcase}, :select => "bsnamw1, bsadd1w1, bsadd2w1, bsadd3w1, bscityw1, bsstcdw1, bszipw1")
if sign_on
order = Order.new(:login => login,
:account_number => query_account_number,
:name => sign_on.bsnamw1,
:address1 => sign_on.bsadd1w1,
:address2 => sign_on.bsadd2w1,
:address3 => sign_on.bsadd3w1,
:city => sign_on.bscityw1,
:state => sign_on.bsstcdw1,
:zip => sign_on.bszipw1)
order.save
order
end
end
end

rails controller stream

Hi i have a controller in rails but it gives me an error
ActiveRecord::StatementInvalid in StreamsController#front_page
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EPOCH FROM posts.created_at) - 1327654606)/9000) desc LIMIT 15' at line 1: SELECT `posts`.* FROM `posts` WHERE ((`posts`.`featured` = 1 OR `posts`.`author_id` = 5)) ORDER BY (ln( 1 + posts.likes_count) + (EXTRACT(EPOCH FROM posts.created_at) - 1327654606)/9000) desc LIMIT 15
The StreamsController#front_page are:
def front_page
stream_responder do
#stream = Stream::FrontPage.new(current_user, params[:offset])
#stream_json = PostPresenter.collection_json(#stream.stream_posts, current_user, lite?: true, include_root: false)
end
end
And PostPresenter
require File.join(File.dirname(__FILE__), '..', '..', 'lib', 'template_picker')
class PostPresenter
include ActionView::Helpers::TextHelper
attr_accessor :post, :current_user
def initialize(post, current_user=nil)
#post = post
#current_user = current_user
#person = #current_user.try(:person)
end
def self.collection_json(collection, current_user, opts={})
collection.includes(:author => :profile).map {|post| self.new(post, current_user).as_json(opts)}
end
def as_json(options={})
{
:id => #post.id,
:guid => #post.guid,
:text => #post.raw_message,
:plain_text => #post.plain_text,
:public => #post.public,
:featured => #post.featured,
:created_at => #post.created_at,
:staff_picked_at => #post.staff_picked_at,
:interacted_at => #post.interacted_at,
:tags => #post.tags.as_json,
:tag_list => #post.tags.map(&:name).join(", "),
:post_type => #post.post_type,
:image_url => #post.image_url,
:object_url => #post.object_url,
:favorite => #post.favorite,
:nsfw => #post.nsfw,
:author => PersonPresenter.new(#post.author, current_user),
:o_embed_cache => #post.o_embed_cache.try(:as_api_response, :backbone),
:mentioned_people => [],
:photos => #post.photos.map {|p| p.as_api_response(:backbone)},
:frame_name => #post.frame_name || template_name,
:parent => (options.fetch(:include_root, true) ? parent(options) : nil),
:title => title,
:next_post => next_post_path,
:previous_post => previous_post_path,
:screenshot_url => #post.screenshot_url,
:screenshot_width => #post.screenshot_width,
:screenshot_height => #post.screenshot_height,
:show_screenshot => self.show_screenshot?,
:has_gif => self.has_gif?,
:conversation_id => #post.conversation_id,
:interactions => options.fetch(:lite?, false) ? lite_interactions : heavy_interactions,
:original => #post.original?
}
end
def next_post_path
Rails.application.routes.url_helpers.next_post_path(#post)
end
def previous_post_path
Rails.application.routes.url_helpers.previous_post_path(#post)
end
def heavy_interactions
PostInteractionPresenter.new(#post, current_user).as_json
end
def lite_interactions
PostInteractionPresenter::Lite.new(#post, current_user).as_json
end
def title
#post.text.present? ? truncate(#post.plain_text, :length => 118) : I18n.translate('posts.presenter.title', :name => #post.author.name)
end
def template_name #kill me, lol, I should be client side
#template_name ||= TemplatePicker.new(#post).template_name
end
def parent(opts={})
PostPresenter.new(#post.parent, current_user).as_json({:include_root => false}.merge(opts)) if #post.respond_to?(:parent) && #post.parent.present?
end
def show_screenshot?
#post.screenshot_url.present?
end
def has_gif?
return false unless #post.photos.present?
return 'gif' if #post.photos.detect{ |p| p.url && p.url.match(".gif") }.present?
end
protected
def person
#current_user.person
end
def user_signed_in?
#current_user.present?
end
end
I dont know where am i do wrong..? badly need help on this
You're closing an unopened parenthesis in the query.
'EPOCH FROM posts.created_at) ...'

How to collect in Rails?

baza_managers = BazaManager.find(:all,
:conditions => ["or_unit_id != ?", 1]).collect {
|mou| [mou.email, mou.or_unit_id]}
respondent_emails = Respondent.find(:all).collect {|r| r.email }
ERROR:
from lib/scripts/baza_sync.rb:26:in `each'
from lib/scripts/baza_sync.rb:26
26 line ↓
baza_managers.each do |moi|
if !respondent_emails.include?(moi)
Respondent.create(:email => moi, :user_id => 1, :respondent_group_id => moi)
end
end
ERROR I GET:
undefined method `email' for ["vadasd#test.test.com", 8]:Array (NoMethodError)
I don't know why I'm getting this error.
try with:
baza_managers = BazaManager.find(:all,
:conditions => ["or_unit_id != ?", 1]).collect {
|mou| [mou.email, mou.or_unit_id]}
respondent_emails = Respondent.find(:all).collect {|r| r.email }
baza_managers.each do |moi|
if !respondent_emails.include?(moi[0])
Respondent.create(:email => moi[0], :user_id => 1, :respondent_group_id => moi[1])
end
end
Fix your code with following:
if !respondent_emails.include?(moi[0])
Respondent.create(:email => moi[0], :user_id => 1, :respondent_group_id => moi[1])
end
I would think there is at least one error not in the way you are using collect but in the logic you write on the last lines when you go through the baza_managers array.
With this code the condition respondent_emails.include?(moi) will be always false because respondent_emails is an array of email addresses but moi is an array like ["vadasd#test.test.com", 8] so they will never match.
I think this mistake made you make an error in the line :
Respondent.create(:email => moi, :user_id => 1, :respondent_group_id => moi)
Because this line will be evaluate as (for example) :
Respondent.create(:email => ["vadasd#test.test.com", 8], :user_id => 1, :respondent_group_id => ["vadasd#test.test.com", 8])
Which is probably not what you want.
Last, I would suggest you to read the debugger rails guide, I often use debugger to figure out where and what is the problem in this kind of code and error.
I would rewrite your code as follows:
baza_managers = BazaManager.all(:conditions => ["or_unit_id != ?", 1]).
collect { |mou| [mou.email, mou.or_unit_id]}
respondent_emails = Respondent.find(:all).collect {|r| r.email }
baza_managers.each do |email, unit_id|
unless respondent_emails.include?(email)
Respondent.create(:email => email, :user_id => 1,
:respondent_group_id => unit_id)
end
end
This solution can be further optimized by using OUTER JOIN to detect missing Respondents
BazaManager.all(
:include => "OUTER JOIN respondents A ON baza_managers.email = A.email",
:conditions => ["baza_managers.or_unit_id != ? AND A.id IS NULL", 1]
).each do |bm|
Respondent.create(:email => bm.email, :respondent_group_id => bm.or_unit_id,
:user_id => 1)
end
The solution can be made elegant and optimal by adding associations and named_scope.
class BazaManager
has_many :respondents, :foreign_key => :email, :primary_key => :email
named_scope :without_respondents, :include => :respondents,
:conditions =>["baza_managers.or_unit_id != ? AND respondents.id IS NULL", 1]
end
Now the named_scope can be used as follows:
BazaManager.without_respondents.each do |bm|
Respondent.create(:email => bm.email, :respondent_group_id => bm.or_unit_id,
:user_id => 1)
end

Resources