Delete from database with specific details in ruby - ruby-on-rails

I try to delete from database all row has a id include in some array or (key,value)
"recp" => "1, 2, 3 , 6, 7 , ........."
ID in #recipient
I try this:
#v = NameOfDatabase.where.not(:id=> #recipient.split(',').map(&:to_i), :conditions => {:thread =>#dis_PI.m_id}).destroy_all
With specific condition i want to remove row with this condition and not include in #recipient
Error in this method :
NoMethodError (undefined method `where' for #<Class:0x7f447f57b140>):
I try multiple code but not working, i put this question multiple time but also not work yet!

From the comments, I learned that you are running a very old version of Ruby on Rails – probably more than 10 years old. With Rails 3.0 the finder methods change completely and therefore all current documentation for Rails will not be helpful anymore. Especially the where method did not exist before Rails 3.0
In such an old version the following should work:
YourModel.destroy_all("id in (?)", #recipient.split(','))
Here you will find the docs of older Rails versions.
The condition is basically just one SQL fragment. When you want to add more conditions then you need to write all conditions in one line like this:
YourModel.destroy_all(
"id IN (?) AND thread = ?", #recipient.split(','), #dis_PI.m_id
)

Related

Rails 4.1 upgrade, having trouble with group

So my 3.2 code looks like this
AssocGenre.includes(:genre).where(attachable_type: Project).count(group: 'genres.name').sort_by{|k,v| -v}.each do
But now it's giving me this error
undefined method `sort_by' for 193:Fixnum
What is the correct syntax for this in rails 4.1 now?
You used to be able to specify the GROUP BY clause when calling count but not anymore. Now you have to specify the GROUP BY with a separate group call. From the fine manual:
count(column_name = nil, options = {})
Count the records.
[...]
If count is used with group, it returns a Hash whose keys represent the aggregated column, and the values are the respective amounts:
Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }
You probably want to include a simple INNER JOIN in the SQL rather than all the extra stuff that includes adds so joins should work better.
So you want to write it this way now:
AssocGenre.joins(:genre)
.where(attachable_type: Project)
.group('genres.name')
.count
.sort_by ...
just have a try :
AssocGenre.includes(:genre).where(attachable_type: Project).count(group:'genres.name').**to_a**.sort_by{|k,v| -v}.each.....

Rails: destroy all but newest based on column

I've got an Authorisation model that has outdated duplicates in it. I want to delete all except the newest based on a :provider column in Authorisation, leaving me with the most recent "linkedin" Authorisation, the most recent "facebook" etc, etc.
How would I write that method? Something like this logically but it gives this error (TypeError: can't convert Authorisation to Array (Authorisation#to_ary gives NilClass)):
old = Authorisation.where(provider: 'facebook') - Authorisation.where(provider: 'facebook').last
Maybe this one:
last_record = Authorisation.where(provider: 'facebook').last
Authorisation.where('created_at < ?', last_record.created_at).delete_all
If there is created_at. In other case you should get all ids except last, and remove records with id from that array.
Another way, is apply not to query. Like:
Authorisation.where.not(id: Authorisation.last.id).delete_all
But it work for Rails 4 only, i think.
Update
This is better:
Authorisation.where('id != ?', Authorisation.last.id).delete_all

Rails 4 + Mongoid 4: Model.only("field").to_a not working as before

I just started a new project in Rails 4 and Mongoid 4 beta and an old behaviour that I used a lot in Mongoid 3 is not working anymore.
Before I used to write Model.only("field").to_a and I would get an array with id and field, all other fields were set to null.
If I try to do this in Mongoid 4 I get: (Object doesn't support #inspect)
Model.only("field").map {|e| e.field} is working although not as before. The id is not included anymore, I get ActiveModel::MissingAttributeError if I try to access the id.
I know I can use Model.pluck("field"), this will not return an array of documents though.
Are these changes real or am I missing something?
EDIT:
As I'm writing this I tried including the id and it's working. ie. Model.only("id", "field").to_a working as before, but my question is still valid. Do I have to include the id now in order to get an array of documents?
This is a new behaviour on Mongoid 4. As you said you can add the "id" field to the only method, and it should work. You also can use the pluck method to get and array of fields you want. Something like:
Model.all.pluck("id", "field"). As you said, You already knew about pluck, and thats the way to go..
cheers.

Rails 3.1 - find using count and select as

I am trying to do the following sql statement in rails:
SELECT COUNT(downloads.title) AS total, downloads.title FROM `downloads` WHERE `downloads`.`member_id` = 60 Group by `downloads`.`title`
I wrote this in rails like this:
Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)
If I run the query straight from the sql server the sql executes correctly but if I run the activerecord version I only get the title back.
I thought this might be because of attr_accessible but this doesnt seem to have made a difference.
any ideas ?
Have you tried to call total method on the collection object ?
This information is not included in the output for object using to_s method, so you probably just do not see it, but total value is there.
downloads = Download.where(:member_id => id).select("COUNT(downloads.title) AS total, downloads.title").group(:title)
downloads.first.total

Rails - Trying to query from a date range...everything from today [duplicate]

This question already has answers here:
Rails ActiveRecord date between
(11 answers)
Closed 9 years ago.
I'm trying to figure the best way to query a date range from rails...I looked around on Google but am unsure about how to use this syntax.
I have a Model that has various events and I like to add to my find condition a caveat that should only show events where the field :st_date is today or later, in effect only show me data that is current, nothing that happened before today.
I ran into a problem because I have no end date to stop the query, I want to query everything from today to next month.
I was thinking something like
#events = Event.find(:all, :conditions => ["start_date between ? and ?",
date.Today, date.next_month.beginning_of_month])
but I get the error undefined local variable or method `date'......
Do I need do anything particular to use the Date class? Or is there something wrong with my query syntax? I would really appreciate any help.
You want Date.today, not date.today. There's nothing wrong with what you're doing, you're just not referencing the date class properly
Furthermore it would be Date.today.next_month.beginning_of_month
I would take it a step further and define a scope in your model for reuse.
# rails 3 example:
# app/models/event.rb
scope :upcoming, lambda {
where("start_date between ? and ?", Date.today, Date.today.next_month.beginning_of_month)
}
# app/controllers/some_controller.rb
#events = Event.upcoming
There is also a great Railscasts episode on scopes in Rails 3:
http://railscasts.com/episodes/202-active-record-queries-in-rails-3
Event.where(:start_date => Date.today..Date.today.next_month.beginning_of_month) also works great.
Take a look at my by_star plugin which lets you do things like:
Event.by_month(Time.now, :field => "start_date")

Resources