I wanna do something like this:
Let's say I have a array of users names ["John", "Mary"], etc...
and I wanna create a array with new User records, where name attribute is initialized by those values. What is the easiest way to do that?
Pass your array into this method:
def create_users(names):
users = []
names.each do |name|
u = User.create(:name => name)
users << u
end
users
end
This:
takes an array of names in
creates an empty array to hold the created users
creates a user for each name and adds the user to the array
returns the array
Found the answer by myself:
["john", "mary"].map{|u| User.new(name: u)}
Related
I want to know if there is an elegant way to merge multiple records from different Models into one new object ?
The case is to build a 'stream' or 'feed' of the app content, like in Facebook.
In detail, each record have multiple and different columns. This is the Models and columns :
Product [name, price]
Post [tagline, image]
Member [name, username, profilepic]
Selection [name, tagline]
The code I tried :
#new_object = #product = Product.find(n) + #post = Product.find(n) + #member = Member.find(n) + #selection = Selection.find(n)
But this is not working because of the differences of fields. I think we have to map into a Hash ?
This is how I will use the final object :
#new_object.each do |stream|
stream.foo
stream.bar
end
So, the goal : take each record and display the content with .each
Luxury : have the oportunity to sort randomly the results.
Many thanks!
You can create a PORO (plain old ruby object) to represent the combined object so something like:
class Stream
attr_accessor :product, :post, :member, :selection
def initialize(attrs)
assign_attributes(attrs)
end
end
Then just initialize and create as many stream objects as you need using Stream.new(attrs). You can create an array of stream objects and loop through them to render or show multiple stream data.
For sorting an array of objects by its attributes you can use
objects.sort_by {|obj| obj.attribute}
I have a table that has alot of data inside it
I'm wanting to do something like this. To grab everything inside a column that matches something else inside another column in another table.
So #car = Cardata.find_by(#carmake)
So, #carmake will be volvo, Typed in a separate form and stored in a table.
In the table Cardata there is a massive list (about 40k records) with different cars ranging from ford to renault to volvo.
The question is. Would #car display all the records that have the word volvo inside?? Or is it the wrong way of doing this? or do i need to label it by column?
Sam
To get all of them:
#cars = Cardata.where(carmake: #carmake).all
To get just the first:
#car = Cardata.where(carmake: #carmake).first
you should be doing:
#car = Cardata.find_by_attribute_name(#carmake) # This will return the first car that matches #carmake.
Assuming attribute_name is model.
You'd do:
Cardata.find_by_model(#carmake)
If you want all the cars that matches #carmake.
You need to do:
Cardata.where(model: #carmake) # this will return an array of all cars with model #carmake.
Assuming you have a column in car data for make, I think you'd want to do something like:
#cars = Cardata.where(make: #carmake).all
I am getting collection of ids [1,2,3,4] in the params and I make a call to an API that will return the array for the corresponding ids. E.g. ["Apple","Orange","Mango"]. How can I update this in my database for the corresponding ids?
For example: the ids which are mentioned above are from my user table. ids = [1,2,3,4], which are primary keys in my user table.
From the API response I got an array of fruit_names for the correlated user_ids. E.g.: ids = [1,2,3,4] and fruit_names = ["a","b","c","d"], where the fruit_name column exists in my user table. How do I update fruit_name from the API response correlated ids in my user table?
You can use each_with_index in combination with update for this:
ids.each_with_index do |id, index|
User.update(id, :fruit_name, fruit_names[index])
end
The above code assumes:
ids = [1,2,3,4]
fruit_names = ["a","b","c","d"]
and that the indexes of those arrays match.
Note that this will execute a query for each item in your ids array. If your ids array is very big this is not going to perform well.
Hash[ids.zip fruit_names].each do |id, fruit|
User.update_all({:fruit_name => fruit}, {:id => id})
end
OR
User.where(:id => ids).each do |usr|
usr.update_attribute(:fruit_name, fruit_names[ids.index(usr.id)])
end
How can I iterate through an array of Activerecord::Relation objects? For instance, let's say I have a Comment class and a User class and I'd like to get all the comment contents from 3 specific users (assuming comments belong to users and user_id is the foreign key):
>> #males = Comment.where('user_id IN (?)', ["123","456","789"])
=> [...] #Array of comment Activerecord::Relation objects
Now I'd like to iterate through comments_from_males and collect all the content attribute contents for each comment in the array.
To clarify, the following works but only for the first male returned, but I need all the comments for all males:
>> #males.first.comments.map(&:content)
=> ["first comment", "second comment"]
comments = #males.map {|user| user.comments.map(&:content)}.flatten
Comment.where('user_id IN (?)', ["123","456","789"]).pluck(:content)
The method pluck
You can use
comments_from_males = #males.collect{|e| e.content if e.gender == "male"}.flatten
It will give you list of all comments from males. Check my db assumptions match.
I have a list of id's, I can store this list in any data type as I will be constructed the id's myself.
How can I fetch all users in this list of id's? I want this to be as fast as possible.
I'm using mysql.
Once I retrieve this list, I want to put the User objects into a hash so I can reference them based on id's like:
user_hash[234]
which will return the user in the hash with the user_id of 234.
user_hash = {}
User.where(:id => [1,2,3,4]).each do |user|
user_hash[user.id] = user
end
You can select rows using an array of IDs like this:
ids = [1, 2, 3, 4]
users = User.find(ids)
This will return an array of User records. If you'd like to map that to a hash so you can access by ID as you described, something like this would work:
ids = [1, 2, 3, 4]
users = {}
User.find(ids).each do |user|
users[user.id] = user
end
users[3] # => #<User id: 3, ...