When User object is nil, which is defined in belongs_to association, I get an error: p.user.title is nil.
How to check that p.user or p.user.title is defined in .map to avoid an error?
#posts = Post.all
results = #posts.map { |p|
{
:id => p.id,
:text => p.text,
:user_title => p.user.title
}
}
Easy as pie.
p.user.try(:title)
The above runs #title on user if user is not nil.
You can use the try method. This will return nil if the user is nil
#posts = Post.all
results = #posts.map { |p|
{
:id => p.id,
:text => p.text,
:user_title => p.user.try(:title)
}
}
Simple - just test p.user before you access title:
#posts = Post.all
results = #posts.map do |p|
{
:id => p.id,
:text => p.text,
:user_title => p.user && p.user.title
}
end
results[i][:user_title] will then be nil if either p.user or p.user.title was.
Related
Controller:
#sites = Site.inspections_enabled_controllers_search.search("test")
#sites.each do |s|
if s == nil
puts "WHAT THE ...?"
end
ap s #print out the site
end
Model:
has_many :inspections_enabled_controllers,
:class_name => 'Controller',
:conditions => ['controllers.inspections_enabled = ?', true]
sphinx_scope(:inspections_enabled_controllers_search) {
{
:joins => :inspections_enabled_controllers
}
}
Returns:
#<Site:0x000000114618b8> {
:id => 156,
:name => "Test Site"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x000000111c41a0> {
:id => 213,
:name => "TestRail V1.5 - SmartLine"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x00000011461200> {
:id => 220,
:name => "Activation Testing"
}
NOTICE the total of SEVEN "-" which are simply empty items in an array.
This worked for me
#sites = Site.inspections_enabled_controllers_search.search("test", :retry_stale => 1)
Reference:
http://pat.github.com/ts/en/searching.html#nils
I couldn't figure out how to pass an argument to a decorator from a controller:
The decorator:
def as_json(options = nil)
{
:name => user.name,
:dob => user.dob
:created_at => user.created_at,
:url => user
}
end
The controller:
format.json { render :json => UserJsonDecorator.new(#user)}
Just passing an extra argument to the new method does not work:
UserJsonDecorator.new(#user,options)
Any ideas?
I was basically using it wrong.
correct form to pass additional arguments is:
UserJsonDecorator.new(#user).to_json(options)
I've spent the last day trying to get this to work in my Rails app, but continually get the response:
{"code"=>"E-C-343", "message"=>"Unrecognized JSON Request."}
BancBox's Documentation is pretty light, so I'm at a bit of an impasse on how to solve this.
Does anyone have an example of a successful API call to createClient at BancBox utilizing REST?
My Post API call utilizing HTTParty:
include HTTParty
format :json
def save_with_bancbox(params = {})
post_params = { :authentication => { :apiKey => BANCBOX_KEY,
:secret => BANCBOX_SECRET
},
:subscriberId => BANCBOX_ID,
:firstName => params[:first_name],
:lastName => params[:last_name],
:ssn => params[:ssn],
:dob => params[:dob],
:address => { :line1 => params[:address_line_1],
:line2 => params[:address_line_2],
:city => params[:city],
:state => params[:state],
:zipcode => params[:zipcode]
},
:homePhone => params[:dob],
:email => params[:email]
}
response = HTTParty.post( BANCBOX_REST_URL,
:body => post_params)
logger.debug "Response -- #{response}"
save!
end
Please try the below code after changing apikey, secret and subscriberid
require "net/https"
require 'rubygems'
require 'json'
require 'httparty'
###########################bancbox.rb in config/initializers#################
BANCBOX_API_KEY = "__KEY__"
BANCBOX_API_SECRET = "__SECRET__"
BANCBOX_SUBSCRIBER_ID = "__SUB_ID__"
BANCBOX_API_URL = "https://sandbox-api.bancbox.com/BBXPortRest"
module Bancbox
class API
include HTTParty
debug_output $stdout
base_uri "#{BANCBOX_API_URL}"
def initialize(u=BANCBOX_API_KEY,p=BANCBOX_API_SECRET)
auth = {:apiKey => u, :secret => p}
#options = {:body => {:authentication =>auth,:subscriberId=>BANCBOX_SUBSCRIBER_ID}, :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }}
end
#USERS
def create_client(options={})
options = options.merge(#options[:body])
#options.merge!({:body => options.to_json})
response = self.class.post("/createClient",#options)
#required_fields- subscriberId,firstName,lastName,ssn,dob,address,homePhone,email
end
def get_schedules(options={})
#options.merge!({:query => {:subscriberId => BANCBOX_SUBSCRIBER_ID}})
#options.merge!({:query => options})
self.class.post("/getSchedules",#options)
end
end
end
b = Bancbox::API .new
b.create_client({:firstName=> "Bipen",:lastName=> "Sasi",:ssn=>"334-444-4444",:dob=> Date.parse("January 1st 1988"), :address=>{:line1=> "4408 walnut st", :line2=>"apt 3r",:city=> "philly",:state=>"pa",:zipcode=>"19110"}, :homePhone=> "2672551161",:email=>"bipen#lokalty.com"})
I think you should POST the request to
https://sandbox-api.bancbox.com/BBXPortRest/createClient
instead of
https://sandbox-api.bancbox.com/BBXPortRest/
Also make sure to set the content type as application/json
In general, you post your request to https://sandbox-api.bancbox.com/BBXPortRest/<method>
I have a method returning this:
format.json { render :json => #call, :include => :customer }
However, I want the #call.created_at to return as a more readable datetime.
How can I do that?
thanks
You can create a method in your model to prettify the time.
class Call < ActiveRecord::Base
def formatted_time
#Pretty time
end
end
format.json { render :json => #call, :include => :customer, :methods => :formatted_time }
How do I translate the following into a named_scope?
def self.commentors(cutoff=0)
return User.find_by_sql("select users.*, count(*) as total_comments from users, comments
where (users.id = comments.user_id) and (comments.public_comment = 1) and (comments.aasm_state = 'posted') and (comments.talkboard_user_id is null)
group by users.id having total_comments > #{cutoff} order by total_comments desc")
end
Here's what I have right now but it doesn't seem to work:
named_scope :commentors, lambda { |count=0|
{ :select => "users.*, count(*) as total_comments",
:joins => :comments,
:conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
:group => "users.id",
:having => "total_comments > #{count.to_i}",
:order => "total_comments desc"
}
}
Ulimately, this is what worked;
named_scope :commentors, lambda { |*args|
{ :select => 'users.*, count(*) as total_comments',
:joins => :comments,
:conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
:group => 'users.id',
:having => ['total_comments > ?', args.first || 0],
:order => 'total_comments desc' }
}
The problem you have is because you replaced selecting from users, comments with an inner join with comments. To properly translate the SQL to a named_scope, use this:
named_scope :commentors, lambda { |cutoff|
{ :select => 'users.*, count(*) as total_comments',
:conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil } },
:from => 'users, comments',
:group => 'users.id',
:having => ['total_comments > ?', cutoff],
:order => 'total_comments desc' } }
And you can't have a default value for lambda parameters, so you can't use |cutoff = 0|.