active record all query from instance - ruby-on-rails

Maybe somebody has an idea how I could solve following problem:
I have a Model and want to query it.
def MyModel < ActiveRecord::Base
# instance method
def all
my_models = MyModel.all
my_models.?? # order my_models ActiveRecord::Relation, that the instance which calls the .all instance method is at first position, and the rest is sorted somehow,..whatever.
end
end
How could I solve that?
EDIT:
Example:
MyModel has a name.
I have four instances of MyModel
MyModel.all => #<ActiveRecord::Relation [#<MyModel id: 1, name: "name1">, #<MyModel id: 2, name: "name2">, #<MyModel id: 3, name: "name3">, #<MyModel id: 4, name: "name4">]>
And I want now:
MyModel.find(1).all => #<ActiveRecord::Relation [#<MyModel id: 1, name: "name1">, #<MyModel id: 2, name: "name2">, #<MyModel id: 3, name: "name3">, #<MyModel id: 4, name: "name4">]>
MyModel.find(2).all => #<ActiveRecord::Relation [#<MyModel id: 2, name: "name2">, #<MyModel id: 1, name: "name1">, #<MyModel id: 3, name: "name3">, #<MyModel id: 4, name: "name4">]>
MyModel.find(3).all => #<ActiveRecord::Relation [#<MyModel id: 3, name: "name3">, #<MyModel id: 1, name: "name1">, #<MyModel id: 2, name: "name2">, #<MyModel id: 4, name: "name4">]>

I believe this accomplishes what you're asking.
def all
self.class.order("case when id = #{id} then 0 else id end")
end

A possible solution would be taking advantage of the fact that an ActiveRecord::Relation instance responds to many of the Array instance methods:
def all
ary = self.class.order(:id)
ary = ary.unshift(self)
ary.uniq
end
However this returns an instance of Array so you can't keep appending additional scopes. Up to you to decide whether that's acceptable in your case.

Related

Move one object in collection of objects in rails

Here is the scenario, I have these objects. Let's assume that this is a User:
The object came from:
#user = User.all
User Object
[<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]
How can I move one object up, for example I want to move User.id == 2? The result I want is shown below.
[<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]
I already got the answer. Here is what I made to made my question above worked.
#users = User.all
user_ids = User.pluck(:id)
user_ids.delete(2)
new_user_ids = [2]
user_ids.each do |id|
new_user_ids << id
end
#users.sort_by { |user| new_user_ids.index(user.id) }
And this made perfect!
We can also do it in a way like this:
Add a new method to Array. lib/rails_extensions.rb
class Array
def swap!(a, b = a - 1)
self[a], self[b] = self[b], self[a]
self
end
end
Then add this in config/environment.rb
require 'rails_extensions'
So we can use the method swap! for arrays and it will swap the object with the one before it. We can do something like this:
#users = User.all #[<#User id: 1>, <#User id: 2>]
user_id = #users.rindex {|user| user.id == 2}
#users = #users.swap!(user_id) #[<#User id: 2>, <#User id: 1>]
is this too ugly?
hash = [{ id: 1}, {id: 2}, {id: 3}]
hash.unshift(hash.delete(hash.select {|h| h[:id] == 2 }.first))
=> [{:id=>2}, {:id=>1}, {:id=>3}]

Replace hash keys with new string in ruby

Company model: There is aa attribute name and company has_many users.
Users model: User belongs to company.
Query:
After the query execution, below is my result.
users = {1360=>[#<User id: 2183, company_id: 1360, name: "XYS">, #<User id: 2184, company_id: 1360, name: "XYS1">], 1361=>[#<User id: 2185, company_id: 1361, name: "ABC">]}
In users object, there is one more column that is company_name which is fetch in query as alias, because I want only company_name not other attributes.
users = {1360=>[#<User id: 2183, company_id: 1360, name: "XYS", company_name="One">, #<User id: 2183, company_id: 1360, name: "XYS", company_name="One">], 1361=>[#<User id: 2185, company_id: 1361, name: "ABC", company_name="Two">]}
Here is the my desired output.
(Key would be company_name and its velue will be array of users info(name and id))
users = {"One"=>[["XYS", 2183], ["XYS1", 2184]], "Two"=>[["ABC", 2185]]}
How can I do that. Because when I try to replace the key(id) with name throughs an error
Try this
users.map{ |_,array| [array.first.company_name, array.map{ |a| [a.name, a.id] }] }.to_h

Different behavior of build method

I was trying to implement a first_or_build method and I encounter a problem when saving my parent : the children were missing.
Everything is working fine when I call my method on the relation like parent.childs.first_or_build(name: 'Foo'); parent.save! whereas nothing happen when I do parent.childs.where(name: 'Foo').first_or_build; parent.save!.
The main objective was to propose a similar behavior than .first_or_create applied to the result of a query for example. (Don't tell me about .first_or_initialize !)
Any idea?
Examples :
# this is not working :(
2.times { |i| parent.childs.where(name: "child #{i}").build { |c| c.age = 42 } } ; parent.childs
=> #<ActiveRecord::Associations::CollectionProxy []>
# while this is
2.times { |i| parent.childs.build { |c| c.name = "#{child #{i}"; c.age = 42 } } ; parent.childs
=> #<ActiveRecord::Associations::CollectionProxy [#<Child name: "child 0", age: 42>, #<Child name: "child 1", age: 42>]>
Sorry, I don't quit understand the part about first_or_build method, so I will just talk about the examples there.
First of all, we know that parent.childs.where(name: "child #{i}") and parent.childs are in different class
parent.children.where(name: "child").class
#=> Child::ActiveRecord_AssociationRelation
parent.children.class
#=> Child::ActiveRecord_Associations_CollectionProxy
so it's clear why their :build method are different, the doc are here
ActiveRecord_Associations_CollectionProxy
ActiveRecord_AssociationRelation
I will try to express my view here.
When you use ActiveRecord_AssociationRelation to build a new child, it will initialize a new Child object, and set its parent_id, but it is just an Child object. In this time, when you execute parent.children, the result is empty.
parent.children.where(name: "child1").build({age: 1})
#=> <Child id: nil, name: "child1", age: 1, parent_id: 1, created_at: nil, updated_at: nil>
parent.children
#=> <ActiveRecord::Associations::CollectionProxy []>
parent.save #=> true
parent.children.reload
#=> <ActiveRecord::Associations::CollectionProxy []>
But when you use ActiveRecord_Associations_CollectionProxy, it will initialize a new Child object, and it will also attach itself to parent, so then when you execute parent.children, the result is not empty.
parent.children.build({name: "child2", age: 2})
#=> <Child id: nil, name: "child2", age: 2, parent_id: 1, created_at: nil, updated_at: nil
parent.children
#=> <ActiveRecord::Associations::CollectionProxy [#<Child id: nil, name: "child2", age: 2, parent_id: 1, created_at: nil, updated_at: nil>]>
parent.save #=> true
parent.children.reload
#=> <ActiveRecord::Associations::CollectionProxy [#<Child id: 3, name: "child2", age: 2, parent_id: 1, created_at: "2015-05-28 17:02:39", updated_at: "2015-05-28 17:02:39">]>
In the second way, parent know it has children, so when it save, it will save its children.I think this is it.

Ruby on Rails - check if object is related to a set of objects (ALL or ANY)

I have a Email model that has_and_belongs_to_many Tags. I would like to check if, given an array of Tags, an Email have ALL of them, and in the other hand, if an Email have ANY of them. In other words, calculate the AND and OR over the membership of an Email to a set of Tags. Unfortunately, I've not been able to find a right way to write this query using ActiveRecord methods. Example:
tags1 = [
#<Tag id: 1, name: "a">,
#<Tag id: 2, name: "b">,
#<Tag id: 3, name: "c">,
#<Tag id: 4, name: "d">
]
tags2 = [
#<Tag id: 1, name: "a">,
#<Tag id: 2, name: "b">
]
tags3 = [
#<Tag id: 3, name: "c">,
#<Tag id: 4, name: "d">
]
tags4 = [
#<Tag id: 1, name: "a">,
#<Tag id: 3, name: "c">,
]
tags5 = [
#<Tag id: 1, name: "b">,
#<Tag id: 3, name: "d">,
]
email = #<Email id: 3, tags: [#<Tag id: 1, name: "a">, #<Tag id: 3, name: "c">]>
email.AND?(tags1) # => true
email.AND?(tags2) # => false
email.AND?(tags3) # => false
email.AND?(tags4) # => true
email.AND?(tags5) # => false
email.OR?(tags1) # => true
email.OR?(tags2) # => true
email.OR?(tags3) # => true
email.OR?(tags4) # => true
email.OR?(tags5) # => false
I'm looking for something like the AND? and OR? methods.
Any ideas? any help would be really appreciated.
UPDATE:
I really didn't express myself very well. What I really need is to find all emails that meet the requirements (AND? or OR?). This is, "Get the list of emails that have ALL the tags in the given tag_list" or "Get the list of emails that have ANY of the tags in the given tag_list". notice this method should act over Email collection and receive tag_list as a parameter.
Also, I would really appreciate if you could explain how does the block syntax work.
Thanks again for your help and for your quick replies! :)
You can define methods like this on class Email
# AND?
def all_tags? tags
tag_ids.sort == tags.map(&:id).sort
end
# OR?
def any_tags? tags
tag_ids.any?{ |tag| tags.map(&:id).include?(tag) }
end
def tag_ids
self.tags.select("id").map(&:id)
end
All caps methods in ruby is not a good practice.
email.AND?(tags1)
Can be written as - email.tags.all? { |tag| tags1.include? tag }
email.OR?(tags1)
Can be written as - email.tags.any? { |tag| tags1.include? tag }

Compare two arrays using include?

I have two arrays:
#all_genres = [#<Genre id: 1, name: "Action", created_at: "2013-03-01 07:44:51", updated_at: "2013-03-01 07:44:51">,
#<Genre id: 2, name: "Adventure", created_at: "2013-03-01 07:44:51", updated_at: "2013-03-01 07:44:51">,
#<Genre id: 3, name: "Animation", created_at: "2013-03-01 07:44:51", updated_at: "2013-03-01 07:44:51">]
#genres = ["Action", "Animation"]
I am trying to find the Genre.id from #genres compared to the #all_genres table. For example my result should be:
#genre_ids = [1, 3]
I have tried this:
#all_genres.each do |g|
if g.name.include?((#genres.each {|g| g}).to_s)
#genre_ids << g.id
end
end
I tried this in my console and it seemed to work but when I put it into my app it returns:
#genre_ids = []
A more rail-sy version:
#genre_ids = Genre.where(name: #genres).pluck(:id)
Or you could try this one-liner:
#genre_ids = #all_genres.select{|g| #genres.include? g.name }.map(&:id)
I'm assuming that you're populating your #genres array with a call to Genre.all.
You could simply do something like this:
Genre.where("name IN (?)", %w[name action]).collect { |x| x.id }
If you want to retrieve the ids for the Genres with those names.

Resources