Rails 3 selecting only values - ruby-on-rails-3

In rails 3, I would like to do the following:
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id")
This works, but i get the following from the DB:
[{"some_other_connection_id":254},{"some_other_connection_id":315}]
Now, those id-s are the ones I need, but I am uncapable of making a query that only gives me the ids. I do not want to have to itterate over the resulst, only to get those numbers out. Are there any way for me to do this with something like :
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id").values()
Or something of that nautre?
I have been trying with the ".select_values()" found at Git-hub, but it only returns "some_other_connection_id".
I am not an expert in rails, so this info might be helpful also:
The "SomeModel" is a connecting table, for a many-to-many relation in one of my other models. So, accually what I am trying to do is to, from the array of IDs, get all the entries from the other side of the connection. Basicly I have the source ids, and i want to get the data from the models with all the target ids. If there is a magic way of getting these without me having to do all the sql myself (with some help from active record) it would be really nice!
Thanks :)

Try pluck method
SomeModel.where(:some => condition).pluck("some_field")
it works like
SomeModel.where(:some => condition).select("some_field").map(&:some_field)

SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id").map &:some_other_connection_id
This is essentially a shorthand for:
results = SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id")
results.map {|row| row.some_other_connection_id}
Look at Array#map for details on map method.
Beware that there is no lazy loading here, as it iterates over the results, but it shouldn't be a problem, unless you want to add more constructs to you query or retrieve some associated objects(which should not be the case as you haven't got the ids for loading the associated objects).

Related

How do I get the results of the Plucky Query inside my controller?

I'm missing something simple - I do not want to access the results of this query in a view.
Here is the query:
#adm = Admin.where({:id => {"$ne" => params[:id].to_s},:email => params[:email]})
And of course when you inspect you get:
#adm is #<MongoMapper::Plugins::Querying::DecoratedPluckyQuery:0x007fb4be99acd0>
I understand (from asking the MM guys) why this is the case - they wished to delay the results of the actual query as long as possible, and only get a representation of the query object until we render (in a view!).
But what I'm trying to ascertain in my code is IF one of my params matches or doesn't match the result of my query in the controller so I can either return an error message or proceed.
Normally in a view I'm going to do:
#adm.id
To get the BSON out of this. When you try this on the Decorated Query of course it fails:
NoMethodError (undefined method `id' for #<MongoMapper::Plugins::Querying::DecoratedPluckyQuery:0x007fb4b9e9f118>)
This is because it's not actually a Ruby Object yet, it's still the query proxy.
Now I'm fundamentally missing something because I never read a "getting started with Ruby" guide - I just smashed my way in here and learned through brute-force. So, what method do I call to get the results of the Plucky Query?
The field #adm is set to a query as you've seen. So, to access the results, you'll need to trigger execution of the query. There are a variety of activation methods you can call, including all, first, and last. There's a little documentation here.
In this case, you could do something like:
adm_query = Admin.where({:id => {"$ne" => params[:id].to_s},:email => params[:email]})
#adm_user = adm_query.first
That would return you the first user and after checking for nil
if #adm_user.nil?
# do something if no results were found
end
You could also limit the query results:
adm_query = Admin.where( ... your query ...).limit(1)

Returning all records in a certain state with state_machine

How would you return a list of records in a certain state with state_machine? Something along the lines of:
#locked = current_user.docs.locked?
Cheers.
EDIT
It seems like current_user.docs.with_state(:locked).all doesn't work either.
A simple current_user.docs.where(:state => "locked") worked, I just thought there'd be a better way.

get model with atleast one relation object in mongoid

I have a Person object which has_many companies. I would like to get the person with atleast one company.
What I can get right now is
Person.where(:company_ids.size => 1)
This will return all the person with one company . But I need something like
Person.where(:company_ids.size.gte => 1)
But it seems , this does not work.
Solution :
sorry for all the trouble, but found out that with previously created objects , I didn't have company_ids ... since I had only added that later. I can get the count with following :
Person.where(:company_ids.exists => true).and("this.company_ids.length > 0")
Thanks everyone for helping out.
I assume company_ids a array field in person document
I am afraid there is no way of specifying conditions in size. But there is a workaround using javascript $where expression
db.person.find({$where: '(this.company_ids.length > 0)'})
am not sure about how to pass this expression in mongoid.
EDIT
yeah you can do this with mongoid too
Person.where("$where" => 'this.company_ids.length >0;' )
You should be able to do:
Person.where("this.company_ids.length > 3")
Did you check doing as
Person.where("this.company_ids >=1")

2nd level cache problem with join query

I want to use Second level Cache for my query with eager loading(query is below wrote in 3 different ways, i use query cache). I have standard one to many association. I set entity cache for parent, child, and association between parent and class. And the 2nd level cache doesn't work because i got exceptions.
I wrote my query in 3 different way:
Criteria:
session.CreateCriteria<DictionaryMaster>().SetFetchMode("DictionaryItems", FetchMode.Eager)
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.SetCacheable(true).SetCacheMode(CacheMode.Normal)
.List<DictionaryMaster>().ToList();
When I invoked this query i got exception "Unable to perform find[SQL: SQL not available]"
I think that the problem exists because I use DistinctRootEntityResultTransformer transform. I will start create my custom transform class and I hope that will work.
Query over:
session.QueryOver<DictionaryMaster>().Fetch(x => x.DictionaryItems).Eager
.TransformUsing(new DistinctRootEntityResultTransformer())
.Cacheable().CacheMode(CacheMode.Normal)
.List<DictionaryMaster>().ToList();
Exception is the same as in Criteria.
Linq:
session.Query<DictionaryMaster>().Fetch(x => x.DictionaryItems).Cacheable().CacheMode(CacheMode.Normal).ToList();
Here error depends from the version of nhibernate in 3.1 a got this error https://nhibernate.jira.com/browse/NH-2587?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel
but in 3.2 version i got this: https://nhibernate.jira.com/browse/NH-2856
Thanks in advance
sJHony I have found solution, but for me is more like workaround. Therefore if you know any other solution give me sign.
I utilize QueryOver without any transformation, the fault of this solution is that the query return elements equal amount of childs. Next I retrieve not multiplied list in memory using distinct.
This solution is ok, but when we add one more Fetch for query, then collection in object also be multiplied, that is why i modified collection type from IList(Bag) to ISet(Set).
Code looks like:
var queryCacheResult =
session.QueryOver<DictionaryMaster>()
.Fetch(x => x.DictionaryItems).Eager
.Cacheable().CacheMode(CacheMode.Normal)
.List<DictionaryMaster>().ToList();
return queryCacheResult.Distinct(new KeyEqualityComparer<DictionaryMaster>(x => x.Code)).ToList();

Help optimizing get all children query (ActiveRecord/Ruby/Rails)

This is just a quick question on performance in an sql query using ruby and rails.
Basically I have a parent model and a bunch of children which have the variable of parent_ID.
I first gather all the parents with a specific condition and then I cycle through each parent finding any children that match.
Unfortunately this is incredibly slow and I was wondering if theres any help going in optimizing it.
#parents = Parent.where(:parent_id => 3) #This is passed in from params
#childrenArray =[]
#parents.each_with_index do |parent, index|
#TOOSLOW
#childrenArray[index] = Child.find(:all,:order=>"id",:conditions =>{:parent_ID=> parent.id})
end
One thing I thought is perhaps I should make an array of all the parent Ids to be searched and then do something like
child.find_by_parent_ID(myarrayofnumbershere)
However I don't know if this would be any better.
Any help or advice appreciated.
I'm very new to SQL and ruby. I'm aware a table joins would have been ideal here but I think I'm a bit late in my development to try it now. Also I need to serve up 2 seperate arrays. one of the parents and one of the children.
Try using the include method, like so:
#parents = Parent.where(:parent_id => 3).include(:children)
Now rails will have fetched the associated children and you should be able to loop over #parents and access their children without additional queries, like so:
#parents.each do |p|
puts "#{p}'s children: #{p.children}"
end