Arrays in Rails - arrays

After much googling and console testing I need some help with arrays in rails. In a method I do a search in the db for all rows matching a certain requirement and put them in a variable. Next I want to call each on that array and loop through it. My problem is that sometimes only one row is matched in the initial search and .each causes a nomethoderror.
I called class on both situations, where there are multiple rows and only one row. When there are multiple rows the variable I dump them into is of the class array. If there is only one row, it is the class of the model.
How can I have an each loop that won't break when there's only one instance of an object in my search? I could hack something together with lots of conditional code, but I feel like I'm not seeing something really simple here.
Thanks!
Requested Code Below
#user = User.new(params[:user])
if #user.save
#scan the invites dbtable and if user email is present, add the new uid to the table
#talentInvites = TalentInvitation.find_by_email(#user.email)
unless #talentInvites.nil?
#talentInvites.each do |tiv|
tiv.update_attribute(:user_id, #user.id)
end
end
....more code...

Use find_all_by_email, it will always return an array, even empty.
#user = User.new(params[:user])
if #user.save
#scan the invites dbtable and if user email is present, add the new uid to the table
#talentInvites = TalentInvitation.find_all_by_email(#user.email)
unless #talentInvites.empty?
#talentInvites.each do |tiv|
tiv.update_attribute(:user_id, #user.id)
end
end

Related

Laravel skip and delete records from Database

I'm developing an app which needs to record a list of a users recent video uploads. Importantly it needs to only remember the last two videos associated with the user so I'm trying to find a way to just keep the last two records in a database.
What I've got so far is the below, which creates a new record correctly, however I then want to delete all records that are older than the previous 2, so I've got the below.
The problem is that this seems to delete ALL records even though, by my understanding, the skip should miss out the two most recent records,
private function saveVideoToUserProfile($userId, $thumb ...)
{
RecentVideos::create([
'user_id'=>$userId,
'thumbnail'=>$thumb,
...
]);
RecentVideos::select('id')->where('user_id', $userId)->orderBy('created_at')->skip(2)->delete();
}
Can anyone see what I'm doing wrong?
Limit and offset do not work with delete, so you can do something like this:
$ids = RecentVideos::select('id')->where('user_id', $userId)->orderByDesc('created_at')->skip(2)->take(10000)->pluck('id');
RecentVideos::whereIn('id', $ids)->delete();
First off, skip() does not skip the x number of recent records, but rather the x number of records from the beginning of the result set. So in order to get your desired result, you need to sort the data in the correct order. orderBy() defaults to ordering ascending, but it accepts a second direction argument. Try orderBy('created_at', 'DESC'). (See the docs on orderBy().)
This is how I would recommend writing the query.
RecentVideos::where('user_id', $userId)->orderBy('created_at', 'DESC')->skip(2)->delete();

OrientDB - find "orphaned" binary records

I have some images stored in the default cluster in my OrientDB database. I stored them by implementing the code given by the documentation in the case of the use of multiple ORecordByte (for large content): http://orientdb.com/docs/2.1/Binary-Data.html
So, I have two types of object in my default cluster. Binary datas and ODocument whose field 'data' lists to the different record of binary datas.
Some of the ODocument records' RID are used in some other classes. But, the other records are orphanized and I would like to be able to retrieve them.
My idea was to use
select from cluster:default where #rid not in (select myField from MyClass)
But the problem is that I retrieve the other binary datas and I just want the record with the field 'data'.
In addition, I prefer to have a prettier request because I don't think the "not in" clause is really something that should be encouraged. Is there something like a JOIN which return records that are not joined to anything?
Can you help me please?
To resolve my problem, I did like that. However, I don't know if it is the right way (the more optimized one) to do it:
I used the following SQL request:
SELECT rid FROM (FIND REFERENCES (SELECT FROM CLUSTER:default)) WHERE referredBy = []
In Java, I execute it with the use of the couple OCommandSQL/OCommandRequest and I retrieve an OrientDynaElementIterable. I just iterate on this last one to retrieve an OrientVertex, contained in another OrientVertex, from where I retrieve the RID of the orpan.
Now, here is some code if it can help someone, assuming that you have an OrientGraphNoTx or an OrientGraph for the 'graph' variable :)
String cmd = "SELECT rid FROM (FIND REFERENCES (SELECT FROM CLUSTER:default)) WHERE referredBy = []";
List<String> orphanedRid = new ArrayList<String>();
OCommandRequest request = graph.command(new OCommandSQL(cmd));
OrientDynaElementIterable objects = request.execute();
Iterator<Object> iterator = objects.iterator();
while (iterator.hasNext()) {
OrientVertex obj = (OrientVertex) iterator.next();
OrientVertex orphan = obj.getProperty("rid");
orphanedRid.add(orphan.getIdentity().toString());
}

Zend_Db_Profiler How to extend class to log rows count

Like I said in the topic,
My team developed social website based on Zend Framework (1.11).
The problem is that our client wants a debug (on screen list of DB queries) with
execution time, how many rows were affected and statement sentence.
Time and statement Zend_DB_profiler gets for us with no hassle, but
we need also the amount of rows that query affected (fetched, update, inserted or deleted).
Please help, how to cope with this task?
This is the current implementation which prevents you from getting what you want.
$qp->start($this->_queryId);
$retval = $this->_execute($params);
$prof->queryEnd($this->_queryId);
Possible solution would be:
Create your own class for Statement, let's say extended from Zend_Db_Statement_Mysqli or what have you.
Redefine its execute method so that $retval is carried on into $prof->queryEnd($this->_queryId);
Redefine $_defaultStmtClass in Zend_Db_Adapter_Mysqli with your new statement class name
Create your own Zend_Db_Profiler with public function queryEnd($queryId) redefined, so it accepts $retval and handles $retval

Remove object from an array of objects

my problem should be rather simple, but i didn't got it.
For example i have the following data from the database:
#user = User.all
then i have an other array of user
other_user = getting_them_from_somewhere_else
Now i iterate over the two arrays and check if some users are still in the database by checking for the emails:
#other_user.each do |o|
#user.each do |u|
if o["email"] == u["user_mail"]
#user.delete(u)
break
end
end
... do something with o ...
end
The method #user.delete(u) deletes the user from the database, but i just want to remove the object u from the array #user.
You can do vise versa
result_users = []
#other_user.each do |o|
#user.each do |u|
if o["email"] != u["user_mail"]
result_users << u
end
end
... do something with o ...
end
here you should use result_users array which has the users you need
You can use:
#other_user.each do |o|
#user.delete_if{|u| u["email"] == o["email"]}
end
It's more simple, and didn't remove of database, only remove in array. =)
How about going the cheaper way... Less work..
create an array of the email addresses that you know about, and don't want anymore.
other_emails = #other_user.map{|o| sanitize(o["email"]) }
#users = User.where("email not in ( #{other_emails.join(',')} )")
There are so many pluses to this approach.
there is only one loop (the map), nothing embedded.
there is only one array resize (the map). We aren't calling delete which is a heavy operation on an array.
We only get records across the network that we care about. Pulling down 1 million records when you only care about a handful is silly. Strive to only read from the DB what you need.
Sometimes letting the database do things is just smarter.
I think you don't need to use #user.email, just:
#users.delete_if {|user| #other_user.include? user}

VisualForce(APEX): Update record with known ID

This is an APEX code related question and is specific to a VisualForce controller class.
Question
I am trying to update a record with a known AccountId. However, when I set the ID in the sObject declaration SalesForce is appending the string "IAR" to the end of the ID!
Can someone please let me know what I am doing that is wrong and if I am going about this in the wrong way than what is the correct way to update a record from a custom method, outside of quicksave() or update().
Description
So basically, the user will come to this page with the id encoded and it will either have an id or a level. This is handled by the function decode() which takes a string; "id" / "level". I then create an Account variable "acc" which will be used to store all of the Account information before we insert or update it with the statement "insert acc;". Since, I cannot set the ID for "acc" with "acc.id = salesForceID" I have decided to set it when "acc" is created. The following APEX code occurs in the constructor when it is declaring the "acc" variable.
URL Variable Passed
/application?id=001Q000000OognA
APEX Controller Class (Abridged)
salesForceID = decode('id');
debug1 = 'salesForceID: ' + salesForceID;
acc = new Account(id = salesForceID);
debug2 = 'Account ID: ' + acc.id;
Debug Output
salesForceID: 001Q000000OognA
Account ID: 001Q000000OognAIAR
Comments
I apologise for the brevity of the code given, this is for security reasons. I am basically trying to set the ID of the acc before I insert/upsert/update it. I appreciate any explanations for why it could be appending "IAR" and or any alternate ways to update a record given an input AccountId. I do understand that if you pass the id in as a URL variable that SalesForce will automatically do this for you. However, I am passing more than one variable to the page as there are three separate use cases.
Thanks for your help.
001Q000000OognA is the "standard" 15-character Salesforce ID. 15-character ID's are case-sensitive.
001Q000000OognAIAR is the case-insensitive 18-character version of that ID.
Either one is fine. You do not need to worry about the difference. If for some reason you really need to use the 15-character version in parameters etc, you can safely truncate the last 3 digits.
More information here: http://www.salesforce.com/us/developer/docs/api/Content/field_types.htm

Resources