apply group on associated attributes ruby on rails by using kickchart to show the geo chart - ruby

I need to apply group on associated attributes to apply it on pie_chart which is the method of kick chart so I just need to fetch the associated object attribute like
= pie_chart array.group(:user)
it returns the user object but I need to apply group on user attribute which is username so please if anybody has solution of this answer me.

You can use Enumerable#group_by (http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-group_by)
Example :
array.group_by { |linker| linker.user.username }
It will create a Hash with the usernames as keys and Array of linkers as values

Related

Why does my forget() method not remove object from collection?

I have a collection of "Tickets", using the random collection utility method I select one from the list. The "Tickets" collection should now remove (or forget) that randomly selected ticket so I can further process that collection. Using the forget method doesn't appear to do what is described in the documentation or (more likely I'm missing something).
Can someone spot whats wrong in my code?
$tickets = Tickets::all();
$total_winners = 5;
$selected_tickets = $tickets->random($total_winners);
$jackpot_winner = $selected_tickets->random();
$selected_tickets->forget($jackpot_winner->id); // this line should remove the $jackpot_winner
When I print the contents of $selected_tickets on lines 3 and lines 5, they have the exact same items, including the $jackpot_winner.
Forget function uses the collection key not the id from the model. To achieve what you want you may use this method:
$selected_tickets = $selected_tickets->except($jackpot_winner->id);
https://laravel.com/docs/8.x/collections#method-except

Removing attributes from an activerecord got via .includes

I am having a really weird problem while attempting to do a very simple thing. I am doing an .includes on a model to get a row of data from the database. On the return object I need to remove certain attributes conditionally. And the final aim is to reinsert this row as a new record based on the changes I make on the attributes using my conditions.
def myUpdate
dbObj = Obj.includes(:name,
:addr1,
:addr2,
:state,
:description).find(params[:id])
#dbObjective.attributes().except('description')
#dbObjective.description = nil
#dbObjective.attributes().delete('description')
# After setting more attributes, persist this object
end
I tried all possibilities that I could think of, but the attribute is just not getting removed. What am I missing? I am on Ruby on Rails 4.2.
includes is used to include associated tables in your query for join queries and eager loading, not for table attributes. You do not need to do anything special to access an object's attributes.
attributes returns a Hash instance containing the record's attributes as key-value pairs, and operating on it will change only the Hash instance itself, not the record.
There are several ways to update attributes. One of the easiest ways is using the built in setter methods given to you by ActiveRecord. If you really want to change attributes using the Hash API you can store the attributes hash in a variable, manipulate the hash, and pass it as an argument to update, which accepts an attributes hash as it's argument.
Using setter methods
def myUpdate
dbObj = Obj.find(params[:id])
dbObj.description = 'new_description'
dbObj.name = 'new_name
dbObj.save
end
Using update
def myUpdate
dbObj = Obj.find(params[:id])
attributes = dbObj.attributes # This is how you would update the object by manipulating the attributes hash
attributes.delete(:description) # this will NOT end up changing the attribute in the DB
attributes[:name] = nil # this will successfully set name to NULL in the DB
dbObj.update(attributes) # pass the manipulated hash to the `update` method to persist the changes
end
deleteing fields from the hash will not have an effect on the persisted object. update only performs an insert on fields present in the hash that have changed.

TYPO3 extbase access sorting

when using the fluid debug array I see a nested array lige this:
building
[+]floor
[+]room
When clicking the + the sub array is expanded sorted by UID and not by the "sorting" as I have specified in my repository.
protected $defaultOrderings = array(
'sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
);
Can I either access the sorting value somehow?
Or can I somehow force TYPO3 to sort its own array after sorting?
The sorting field should not be manually set.
If you want to sort the entries please use the DataHandler like the Typo3 Backend.
Here is a solution:
TYPO3 CommandController: How to set table field "sorting" of Extbase Object?
By "clicking the +", you mean that the subobjects aren't sorted the way you specified in the TCA?
The sorting is lost on the subobjects because Extbases PersistenceRepository by default only sorts by the order specified in the object itself. But thats no biggie, you just have to specify to order by the subproperty, either with the defaultOrderings property or when building the query:
class FloorRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {
// Order by BE sorting
protected $defaultOrderings = array(
'sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
'room.sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
);
...
}
This should give you the Rooms of a Floor, Ordered by the sorting of the Floors, and in each Floor, the Rooms sorted by their sorting.
You can access the sorting property by defining it as integer in your model and creating the related getter (setter if needed)
protected $sorting

How to create an value array for a specific key in ruby hash?

There are user and user_level models in our rails app. In user_level there is a field called user_group_id. The relationship is userhas_manyuser_levels. We would like to generate an array of the user_group_id (in user_level) for a given user_id.
For a given user_id, its user_levels could be retrieved as :
u = User.find(user_id)
ul = u.user_levels
There may be multiple user_levels for a user. How to create an array of user_group_id from ul with ruby map (or some other ruby method(preferable ruby))? thanks.
Try this,
user = User.find(user_id)
user.user_levels.pluck(:user_group_id)
or this,
user.user_levels.map(&:user_group_id)
The first makes a separate database query selecting just the :user_group_id. For example, in MySQL it would call SELECT user_levels.user_group_id ....
The second collects the :user_group_id from the fetched user_levels.
You are indeed looking for map
user_group_ids = ul.map{|x| x.user_group_id}
Or with the shorthand:
user_group_ids = ul.map(&:user_group_id)
You might also want to have only different ids and no nils
user_group_ids = ul.map(&:user_group_id).uniq.compact

Interacting With Class Objects in Ruby

How can I interact with objects I've created based on their given attributes in Ruby?
To give some context, I'm parsing a text file that might have several hundred entries like the following:
ASIN: B00137RNIQ
-------------------------Status Info-------------------------
Upload created: 2010-04-09 09:33:45
Upload state: Imported
Upload state id: 3
I can parse the above with regular expressions and use the data to create new objects in a "Product" class:
class Product
attr_reader :asin, :creation_date, :upload_state, :upload_state_id
def initialize(asin, creation_date, upload_state, upload_state_id)
#asin = asin
#creation_date = creation_date
#upload_state = upload_state
#upload_state_id = upload_state_id
end
end
After parsing, the raw text from above will be stored in an object that look like this:
[#<Product:0x00000101006ef8 #asin="B00137RNIQ", #creation_date="2010-04-09 09:33:45 ", #upload_state="Imported ", #upload_state_id="3">]
How can I then interact with the newly created class objects? For example, how might I pull all the creation dates for objects with an upload_state_id of 3? I get the feeling I'm going to have to write class methods, but I'm a bit stuck on where to start.
You would need to store the Product objects in a collection. I'll use an array
product_collection = []
# keep adding parse products into the collection as many as they are
product_collection << parsed_product_obj
#next select the subset where upload_state_ud = 3
state_3_products = product_collection.select{|product| product.upload_state_id == 3}
attr reader is a declarative way of defining properties/attributes on your product class. So you can access each value as obj.attribute like I have done for upload_state_id above.
select selects the elements in the target collection, which meet a specific criteria. Each element is assigned to product, and if the criteria evaluates to true is placed in the output collection.

Resources