NULL value in :conditions => - ruby-on-rails

Contract.all(:conditions => ['voided == ?', 0]).size
=> 364
Contract.all(:conditions => ['voided != ?', 0]).size
=> 8
Contract.all.size
=> 441
the 3 numbers does not added up (364 + 8 != 441). What's the proper way write the :conditions to count the rows which the voided column value is NULL or equal to zero?

Contract.all(:conditions => {:voided => nil})
or
Contract.all(:conditions => ['voided IS NULL'])

Contract.all(:conditions => ["voided is ?", nil]).size
Contract.all(:conditions => ["voided is not ?", nil]).size

Related

rails 4 syntax changes

How can I rewrite this below code with rails 4 new syntax.
Tracker.find(:all, :joins => :projects,
:select => "DISTINCT #{Tracker.table_name}.*",
:conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt],
:order => "#{Tracker.table_name}.position")
Below is the equivalent way :
Tracker.joins(:projects)
.where("#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status <> #{STATUS_ARCHIVED}", lft, rgt)
.select("DISTINCT #{Tracker.table_name}.*")
.order("#{Tracker.table_name}.position")

NHibernate QueryOver with WhereRestriction as OR

I have this query but I can't seem to find how I set my WhereRestrictionOn as an OR. Now they function as AND but I want one OR the other.
var privateInfo = Session.QueryOver<ConContact>()
.JoinAlias(c => c.PrivateInfos, () => pi)
.WhereRestrictionOn(c => c.FirstName).IsLike(_selectedFirstLetter + "%")
.WhereRestrictionOn(c => c.LastName).IsLike(_selectedFirstLetter + "%") // todo: change to firstname OR lastname
.Where(c => c.Status == ContactStatus.Approved)
.Select(
Projections.Property("pi.Id").WithAlias(() => sri.Id),
Projections.Property("FirstName").WithAlias(() => sri.Name), //todo: get fullname here => Add concontact object in privateinfo
Projections.Property("pi.Address").WithAlias(() => sri.Address),
Projections.Constant("Contact").WithAlias(() => sri.Type)
)
.TransformUsing(Transformers.AliasToBean<SearchResultInfo>())
.List<SearchResultInfo>()
.ToList();
Any help is much appreciated thx!
SOLUTION:
var privateInfo = Session.QueryOver<ConContact>()
.JoinAlias(c => c.PrivateInfos, () => pi)
.Where(
Restrictions.Disjunction()
.Add(Restrictions.Like("FirstName", _selectedFirstLetter + "%"))
.Add(Restrictions.Like("LastName", _selectedFirstLetter + "%"))
)
.Where(c => c.Status == ContactStatus.Approved)
.Select(
Projections.Property("pi.Id").WithAlias(() => sri.Id),
Projections.Property("FirstName").WithAlias(() => sri.Name), //todo: get fullname here => Add concontact object in privateinfo
Projections.Property("pi.Address").WithAlias(() => sri.Address),
Projections.Constant(NewObjectType.Contact).WithAlias(() => sri.Type)
)
.TransformUsing(Transformers.AliasToBean<SearchResultInfo>())
.List<SearchResultInfo>()
.ToList();
The top level .Where() family (including WhereRestrictionOn) is always joined with AND. So we have to explicitly use something like:
Restrictions.Or(restriction1, restriction1)
Restrictions.Disjunction().Add(restriction1).Add(restriction2).Add(...
So, this could be our case:
.Where(
Restrictions.Disjunction()
.Add(Restrictions.On<ConContact>(c => c.FirstName)
.IsLike(_selectedFirstLetter, MatchMode.Start))
.Add(Restrictions.On<ConContact>(c => c.LastName)
.IsLike(_selectedFirstLetter, MatchMode.Start))
// more OR ...
//.Add(Restrictions.On<ConContact>(c => c.MiddleName)
// .IsLike(_selectedFirstLetter, MatchMode.Start))
)
As discussed here: 16.2. Simple Expressions, for simple stuff we can even use || (cited small example):
.Where(p => p.Name == "test name" && (p.Age > 21 || p.HasCar))

rails, syntax error, unexpected ','

I have several conditions in my search.
#events = Event.search(params[:search],
:conditions => {:group_size => 1, :days => 1})
The above code is working fine. However, if I want to replace the hash with a private method, I get syntax error
syntax error, unexpected ',', expecting tASSOC
:conditions => {group_size_condition, :days => 1},
Code is as follow
#events = Event.search(params[:search],
:conditions => {group_size_condition, :days => 1})
private
def group_size_condition
if params[:groupsize] == 'single (1)'
:group_size => 1
elsif params[:groupsize] == 'couple (2)'
:group_size => 2
elsif params[:groupsize] == 'small group(3-5)'
:group_size => 3..5
else
nil
end
end
Thanks in advance
That will be work
#events = Event.search(params[:search],
:conditions => group_size_condition.merge(:days => 1))
private
def group_size_condition
case params[:groupsize]
when 'single (1)' then {:group_size => 1}
when 'couple (2)' then {:group_size => 2}
when 'small group(3-5)' then {:group_size => 3..5}
else
{}
end
end
I think you missed :group_size key
#events = Event.search(params[:search],
:conditions => {:group_size => group_size_condition, :days => 1})
I think perhaps you want to actually pass the string, as in:
def group_size_condition
if params[:groupsize] == 'single (1)'
':group_size => 1'
elsif params[:groupsize] == 'couple (2)'
':group_size => 2'
elsif params[:groupsize] == 'small group(3-5)'
':group_size => 3..5'
else
nil
end
end

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

rails active record - complicated conditions clause

this works:
ids = [1,2]
varietals = Varietal.find(:all, :conditions => [ "id IN (?)",ids])
But what I want to do is that plus have a condition of: deleted => false
varietals = Varietal.find(:all, :conditions =>{ :deleted => false})
any ideas?
am i going to have to use find_by_sql?
I would handle this with a named_scope to communicate intent and foster re-use:
named_scope :undeleted,
:conditions => { :deleted => false }
Then you can simply use:
varietals = Varietal.undeleted.find([1,2])
You can do it a few ways, but this is the most straight forward:
varietals = Varietal.find( [1,2], :conditions => { :deleted => false })
You can see in the docs that the first parameter of find can take an integer or an array.
ids = [1,2]
varietals = Varietal.find(:all, :conditions => {:id => ids, :deleted => false})
This should work, haven't tested it though.
From the docs:
An array may be used in the hash to
use the SQL IN operator:
Student.find(:all, :conditions => { :grade => [9,11,12] })

Resources