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.
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")
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
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).
In a Rails app, I have a model, Machine, that contains the following named scope:
named_scope :needs_updates, lambda {
{ :select => self.column_names.collect{|c| "\"machines\".\"#{c}\""}.join(','),
:group => self.column_names.collect{|c| "\"machines\".\"#{c}\""}.join(','),
:joins => 'LEFT JOIN "machine_updates" ON "machine_updates"."machine_id" = "machines"."id"',
:having => ['"machines"."manual_updates" = ? AND "machines"."in_use" = ? AND (MAX("machine_updates"."date") IS NULL OR MAX("machine_updates"."date") < ?)', true, true, UPDATE_THRESHOLD.days.ago]
}
}
This named scope works fine in development mode. In production mode, however, it returns the 2 models as expected, but the models are empty or uninitialized; that is, actual objects are returned (not nil), but all the fields are nil. For example, when inspecting the return value of the named scope in the console, the following is returned:
[#<Machine >, #<Machine >]
But, as you can see, all the fields of the objects returned are set to nil.
The production and development environments are essentially the same. Both are using a SQLite database. Here is the SQL statement that is generated for the query:
SELECT
"machines"."id",
"machines"."machine_name",
"machines"."hostname",
"machines"."mac_address",
"machines"."ip_address",
"machines"."hard_drive",
"machines"."ram",
"machines"."machine_type",
"machines"."use",
"machines"."comments",
"machines"."in_use",
"machines"."model",
"machines"."vendor_id",
"machines"."operating_system_id",
"machines"."location",
"machines"."acquisition_date",
"machines"."rpi_tag",
"machines"."processor",
"machines"."processor_speed",
"machines"."manual_updates",
"machines"."serial_number",
"machines"."owner"
FROM
"machines"
LEFT JOIN
"machine_updates" ON "machine_updates"."machine_id" = "machines"."id"
GROUP BY
"machines"."id",
"machines"."machine_name",
"machines"."hostname",
"machines"."mac_address",
"machines"."ip_address",
"machines"."hard_drive",
"machines"."ram",
"machines"."machine_type",
"machines"."use",
"machines"."comments",
"machines"."in_use",
"machines"."model",
"machines"."vendor_id",
"machines"."operating_system_id",
"machines"."location",
"machines"."acquisition_date",
"machines"."rpi_tag",
"machines"."processor",
"machines"."processor_speed",
"machines"."manual_updates",
"machines"."serial_number",
"machines"."owner"
HAVING
"machines"."manual_updates" = 't'
AND "machines"."in_use" = 't'
AND (MAX("machine_updates"."date") IS NULL
OR MAX("machine_updates"."date") < '2010-03-26 13:46:28')
Any ideas what's going wrong?
This might not be related to what is happening to you, but it sounds similar enough, so here it goes: are you using the rails cache for anything?
I got nearly the same results as you when I tried to cache the results of a query (as explained on railscast #115).
I tracked down the issue to a still open rails bug that makes cached ActiveRecords unusable - you have to choose between not using cached AR or applying a patch and getting memory leaks.
The cache works ok with non-AR objects, so I ended up "translating" the stuff I needed to integers and arrays, and cached that.
Hope this helps!
Seems like the grouping may be causing the problem. Is the data also identical in both dev & production?
Um, I'm not sure you're having the problem you think you're having.
[#<Machine >, #<Machine >]
implies that you have called "inspect" on the array... but not on each of the individual machine-objects inside it. This may be a silly question, but have you actually tried calling inspect on the individual Machine objects returned to really see if they have nil in the columns?
Machine.needs_updates.each do |m|
p m.inspect
end
?
If that does in fact result in nil-column data. My next suggestion is that you copy the generated SQL and go into the standard mysql interface and see what you get when you run that SQL... and then paste it into your question above so we can see.