With activerecord, how do I do a .find using an array of ids when I know that some may be missing? - activerecord

I have an array of ids. Some may be in my table, some may not. I want to return the ones in the table and then create rows for missing ones. If I do a Model.find(array) I get an ActiveRecord::RecordNotFound exception if any of them are missing. The workaround I'm using is to do a .exists? for each id, but this makes for many db calls, slowing things down.
Is it possible to do a Model.find(array) without having to test each one with .exists?

Looks like find_by_id has been deprecated, but it got me looking in the right direction. Model.where(id: array) seems to do the trick.

If you use find_by_id ActiveRecord will not throw an error and SQL will only collect the existing ids.
Model.find_by_id(array)

Related

grails sort by date not working

I have domain object named Roll and on the list page i want to show the user all the Roll objects iterating through a list, sorted by entry date.
Here is the code i am using
[rollList: Roll.findAll(sort:"rollDate"){userid==uid}]
rollDate is a field inside the Roll object with data type java.util.Date
Any suggestion on why the output is not sorted by rollDate. When i iterate through the rollList on the gsp page it is not sorted.
Also, on the Roll domain object i have even put this code, but it's still not sorting.
static mapping = {
sort "rollDate"
}
Thank you.
Why aren't you using the dynamic finders?
Roll.findAllByUserid( uid, [ sort:"rollDate", order: 'desc'] )
should work.
The findAll( Map, Closure ) method appeared not a long time ago, perhaps it was not tested well...
You might need to use order in your query as well, then add order to it
[rollList: Roll.findAll(sort:"rollDate", order: 'desc'){userid==uid}]
After trying both the solutions mentioned it still didn't work. So i thought something might be wrong on the front end.
While researching more i found that since i was using jquery data tables it used to re order the sorting. The solutions i found was here
jQuery DataTable rows order
So both the answers above are correct. The issue was actually with jquery data tables.

Can you data-bind a composite id in Grails such that it (or parts of it) becomes updateable?

I am trying to read through the dataBind documentation, but it's not all that clear:
http://grails.org/doc/2.1.0/ref/Controllers/bindData.html
I have a composite id composed of 4 columns, and I need to update one of those. It refuses to .save() and doesn't even throw an error. Is there some configuration that will allow me to change these values and save the model?
If I delete it and create a new record, it will bump the rowid, which I was using on the browser side with datatables/jeditable, and it's not really an option. However, even if I include all the parameters with an empty list:
def a = WaiverExemption.find("from WaiverExemption as e where e.exemptionRowId = ?", [params.rowid])
a.properties = params
bindData(a, params, [include: []])
a.save(flush: true, failOnError: true)
This does not seem to work. I've also tried naming the columns/properties explicitly both by themselves and also with "id".
I was confused on what bindData() actually does. Still confused on that.
If you have a composite id in Grails and wish to change one or more of the column values, save() will never ever execute as suggested in the question. Instead, you'll want to use .executeUpdate(). You can pass in HQL that updates (though most of the examples on the web are for delete) the table in question, with syntax that is nearly identical to proper SQL. Something along the lines of "update domain d set d.propertyName = ?" should work.
I do not know if this is a wise thing to do, or if it violates some philosophical rule of how a Grails app should work, but it will actually do the update. I advise caution and plenty of testing. This crap's all voodoo to me.

How to massive delete in php-activerecord where id NOT in list?

I'm running a CodeIgniter application with PHP-Activerecord installed and I need to do a massive delete. The PHP-AR library supports massive update and delete, but the function only takes the ids that you want to delete/update. I'm trying to do a massive delete where the ids are NOT in the list.
delete from table where id not in (1,2,3...,500)
Unfortunately, the PHP-Activerecord website is of no help, and their forums are so horribly built (no search... seriously?) that I'm truly stuck.
edit: Please note, CodeIgniter's built-in ORM is not the same as PHP-Activerecord. Just thought I'd clarify that.
A bit late but this may help someone else. In PHPActiveRecord, do it in this way:
$ids_to_delete = array(1,2,3);
YourModel::delete_all(array('conditions' => array('id NOT IN (?)', $ids_to_delete)));
Ref: http://www.phpactiverecord.org/docs/ActiveRecord/Model#methoddelete_all
SInce active record is actually build string query with function, you can use this method:
- make your list as string
- make this query : $this->db->where('id not in',$string)->delete('table')

how to group objects in an array Ruby

I have an array of users who are managers.
However there are repeated Users.
I would like to group them so that there is only one instance of each User in the array.
What would be the best way to go about this?
#managers.sort_by{|obj| obj.id} # Just sorted the data but did not eliminate duplicats
#managers.group_by{|u|u.name} # just created a bunch of arrays for each name
Use the uniq method, which returns a new array with duplicates removed.
#managers.uniq
If by duplicate you mean the same object ID, then you can do the following:
#managers.uniq.group_by(&:name)
Filtering the array feels like fixing symptoms. Why does the array contain rubbish in the first place?
I would suggest adding a manager? method to your User model that returns true if the user is a manager. Then you could to something like
#managers = User.select &:manager?
and get an array that only contains managers.
you can also do
Manager.select('DISTINCT user_id')
to get a clean array in the first place, whith better performance.

How do I get documents more recent than a particular document in Mongoid?

I am trying to do something like this in mongoid:
User.any_in(:uid => friends).and(:id.gt => "4d391ab448fa7d389b000000").entries
But looks like Mongoid ID cannot be compared this way. How do I achieve the above without resorting to using Mongoid::Timestamps ?
Thanks!
Why would you not want to use timestamps?
Using ids in this way will not give you the behavior you want.
The id of the document will depend not only on the order of insertion but also on what machine the id was generated on.
Timestamps are definitely your best bet here.
I guess you can use server side javascript to process the values but that would be less efficient and less secure if you care for these properties.

Resources