My array contains a varying amount of objects. I need to iterate through the array and save each object id as a unique variable. Given the amount of objects within the array will vary, how should I do this?
"items"=>[{"id"=>"B00668BTCI"}, {"id"=>"B0041KJSL2"}]
I need to save the information to a new object that can support up to 16 IDs. #object.id_one, #object.id_two, etc...
The suitable way to save your data all depends upon how you want to reference it or access it later. Meta-programming is interesting and fun, but may be overkill depending upon your needs. You will need to determine that after looking at the choices. An alternative way is in an array:
array_of_ids = items.map(&:values).flatten
Or
array_of_ids = items.map { |item| item["id"] }
Then all of the IDs are in the array array_of_ids and becomes, in your example:
["B00668BTCI", "B0041KJSL2"]
Accessible by:
array_of_ids[0] # first id
array_of_ids[1] # second array
...
You need to do some meta-programming here...
Here is a post for you, it has an answer (by Chirantan) that shows how to create instance variables dynamically.
Hope this helps.
EDIT
Just in case you get interested to learn more, I have also found a good article about creating methods dynamically, check it out.
Dynamically adding class methods in Ruby by Ryan Angilly
Related
Good afternoon fellow developers,
I have come across a scenario where I found myself needing to retrieve the list of pending changes from my model and editing a specific property of those entries before sending them to my back-end.
These are new entities I created using the createEntry() method of the OData model v2. But, at the time of creation of said entities, I do not possess the value I need to add to them yet. This is the list of entities I retrieve by using the getPendingChanges() method on my model:
What I need to do is to loop through each of these newly created entities and set a specific property into them before actually sending them to my back-end with the submitChanges() method. Bare in mind that these are entry objects created by the createEntry() method and exist only in my front-end until I am able to submit them with success.
Any ideas that might point me in the right direction? I look forward to reading from you!
I was able to solve this issue in the following way:
var oPendingChanges = this.model.getPendingChanges();
var aPathsPendingChanges = $.map(oPendingChanges, function(value, index) { return [index];});
aPathsPendingChanges.forEach(sPath => oModel.setProperty("/" + sPath + "/PropertyX","valueFGO"));
The first two instructions retrieve the entire list of pendingChanges objects and then builds an array of paths to each individual entry. I then use that array of paths to loop through my list of pending changes and edit into the property I want in each iteration of the loop. Special thanks to the folks at answers.sap for the guidance!
I have a table with this columns:
param_id
val_value
val_flag
date_value
tmp_value
tmp_flag
And I have an array of elements, I always have param_id and date_value, but sometimes i have val columns and other times I have tmp columns.
I use $data->save() because sometimes I need to create a new register in db and other times I need to update the register with param_id and date_value.
The question is: Is there any way to do an insert/update but when is an update, only update tmp columns or val columns? I think a find First is my only option, but maybe there is another way.
Thank you.
[EDIT]
I'm trying with the whitelist but it does not work. Let me explain how the method works: I get a request to a web service, process the xml and generate an array of elements with the information collected, after processing these elements I have an array of elements of the class appropriate to save, but these may be new or existing and may contain tmp or val values, I have tried with this but I still change the values to null.
if ($medida->tipo == 'temporal'){
$whiteList = array('val_value','val_flag');
}else if ($medida->tipo == 'validado'){
$whiteList = array('tmp_value','tmp_flag');
}
$dato->save(null, $whitelist);
I do not have data of the post, I use null instead, I have also tried to use an array with the manual assignment of the data obtaining the same result.
Here are two options that can help you:
1) Use 'whitelist' for the save() method.
$obj->save($this->request->getPost(), ['tmp_1', 'tmp_2']);
More info in the documentation.
2) Use the 'Event Manager'.
The methods beforeCreate() and beforeUpdate() will be useful so you can decide which fields to use.
More info in the documentation.
Also if you really want phalcon phql to update only columns which changed you need to enable dynamic update.
I want to iterate over the properties of my models in Objective-C. I tried this. Created PropertyUtil class with method classPropsFor:(Class)klass. Please find the attachment. Used objc/runtime.h. The code which I got from the net. In my viewcontroller I am doing this. [PropertyUtil classPropsFor:[self.user class]];. self.user is User model class. What I want to know is how can i iterate over the properties of my models, let's username, password and those values.
You may want to manually list all properties your model has.
Just add a method to your model:
+(NSArray*) propList {
return #[#"prop1", #"prop2"];
}
Then just use key-value coding to get the value
[someObject valueForKey:#"prop1"];
That's pretty straight and simple way if you wish to avoid Obj-C meta functions. Since you add your properties manually anyway, you may also add them in your list as well.
That's of course, if you don't have a large amount of models already and you wish do them all at once.
I am using an API and receiving a array of hashes. Lets say:
array = client.getObjects(123) //where 123 is some collection of object ID
I want to add some additional attributes to the array to use later in my view, like:
<%= array.getRequestor %> // return a string
What is the easiest way to do this? I was thinking about creating a new class that extends array but I wanted to know can I just add a string "requestor" attribute a lot easier?
Thanks
Extending a core class is not a good idea in general, especially when the additional responsibilities you want to add in are specific to your functional domain.
6 months down the line, somebody (perhaps yourself) will be trying to debug the code and wondering why does Array expose a random custom method.
It would be better to explicitly define your custom view object, perhaps by using a Struct, eg:
# my_view_object.rb
class MyViewObject < Struct.new(:hash)
def getRequestor
# manipulate / return specific hash data
end
end
# controller
#view_obj = MyViewObject.new(client.getObjects(123))
# view
#view_obj.hash # original hash
#view_obj.getRequestor # your custom attribute
Note that the intent of a Struct is to represent a custom data structure, not behaviour. If your custom method needs to do unrelated work, you might want to use a PORO (Plain Old Ruby Object) instead.
I'd say that extending Array sounds like a really bad idea. I would suggest you instead wrap the array in hash of your own. For example
my_hash = {getRequestor: ?, array: array}
and then use it like
<%= my_hash.getRequestor %>
as in your example code.
I've got a domain class, Widget, that I need to delete all instances out of -- clear it out. After that, I will load in fresh data. What do you suggest as a mechanism to do this?
P.S. Note this is not at bootstrap time, but at "run-time".
The easiest way is to use HQL directly:
DomainClass.executeUpdate('delete from DomainClass')
DomainClass.findAll().each { it.delete() }
If you want to avoid any GORM gotchas, such as needing to delete the object immediately and checking to make sure it actually gets deleted, add some arguments.
DomainClass.findAll().each { it.delete(flush:true, failOnError:true) }
Fairly old post, but still actual.
If your table is very large (millions of entries), iterating using findall()*.delete() might not be the best option, as you can run into transaction timeouts (e.g. MySQL innodb_lock_wait_timeout setting) besides potential memory problems stated by GreenGiant.
So at least for MySQL Innodb, much faster is to use TRUNCATE TABLE:
sessionFactory.currentSession
.createSQLQuery("truncate table ${sessionFactory.getClassMetadata(MyDomainClass).tableName}")
.executeUpdate()
This is only useful if your table is not referenced by other objects as a foreign key.
From what I learnt, I agree with #ataylor the below code is fastest IF there are no associations in your domain object (Highly unlikely in any real application):
DomainClass.executeUpdate('delete from DomainClass')
But if you have assiciations with other domains, then the safest way to delete (and also a bit slower than the one mentioned above) would be the following:
def domainObjects = DomainClass.findAll()
domainObjects.each {
it.delete(flush:it==domainObjects.last, failOnError:true)
}
If you have a list of objects and want to delete all elements, you can use * operator.
'*' will split the list and pass its elements as separate arguments.
Example.
List<Book> books = Book.findAllByTitle('grails')
books*.delete()