Rails 3 getting wrong count in query - ruby

I'm trying to get the number of messages that haven't been read.
The Message model has a column called read_at. If the message has been read there is a value in read_at, if it's unread then that value is nil.
I have one read message and one unread message. I get 0 unread messages (I should be getting 1). This is the code:
Message.all(:conditions =>
['website_id = ? AND read_at = ?', current_website.id, nil]).count
It seems that the query is right, since the development log is showing me
Message Load (0.2ms) SELECT "messages".* FROM "messages"
WHERE (website_id = 2 AND read_at = NULL)

instead of read_at = NULL
try read_at is null, it is a SQL thing.
:conditions => ['website_id = ? AND read_at is ?', current_website.id, nil]
Here is a short article on SQL nulls, and how to use them:
http://www.w3schools.com/sql/sql_null_values.asp
Hope it helps

Though the problem is the one pointed by #pdjota, you should use Rails 3 notation, here is how I would write it:
Message.where('website_id = ? AND read_at IS NULL', current_website.id).count

Related

Valid unprepared query not functioning in migrations

(Laravel 5.6)
I'm having issues executing DB::unprepared query in a laravel migration. The query is valid, as I can copy-paste it directly in my db management app. But within an unprepared query, nada. I'm not getting any errors whatsoever.
I've tried using DB::raw and a combination of the two, as seen in other posted questions, to no avail. Anybody spot any obvious errors that I'm missing? TIA.
DB::unprepared(
'Update protocols AS P
INNER JOIN (
SELECT auditable_id, updated_at
FROM logs
WHERE auditable_type = \'App\\Protocol\'
AND event = \'updated_status\'
AND new_values LIKE \'%pending irb specialist review%\'
OR
auditable_type = \'App\\Protocol\'
AND event = \'updated_status\'
AND new_values LIKE \'%pending faculty sponsor approval%\'
)
AS L ON L.auditable_id = P.id
SET P.submitted_on = L.updated_at
WHERE P.id = L.auditable_id'
);

Laravel Eloquent: get dialog based on messages

I have messages table with structure like: id, to_id, from_id ...
I need to write Eloquent query that gives me dialogs for specific user as result. Every dialog should have one last message (no matter incoming or sent) and all ordered by ctreated_at desc.
For example getting whole dialog by id of companion:
$messages = Message::with(array_keys($fields->getRelations()))
->select($select)
->whereRaw('from_id = ? and to_id = ? ', [auth()->id(), $args['user_id']])
->orWhereRaw('from_id = ? and to_id = ? ', [$args['user_id'], auth()->id()])
->orderByDesc('created_at');
But before that i need a list of dialogs available to get.
Trying
$dialogUsers = Message::where('to_id', auth()->id())
->orWhere('from_id', auth()->id())
->select(['from_id', 'to_id'])
->distinct();
but i need to get messages too and in desc order

Sequel SELECT count(id) FROM tablename WHERE username = "alpha"

I can't seem to get this query right. Sequel implementation of:
SELECT count(id) FROM users WHERE username = "alpha" AND status = "new"
Here's what I have so far:
db = Sequel.connect('postgres://me:pw#0.0.0.0:5432/dbname)
u = db[:users]
puts "Total users: #{u.count}" # this is correct
puts db.where(:username => "alpha", :status => "new").count
I've tried various direct SQL and that doesn't seem to work either. It smells like this is remedial, but the connectivity is fine, and I can replicate the exact SQL which doesn't come back the same.
You forgot to select the table. You want this:
db[:users].where(username:'alpha', status:'new').count
For SQLite3, this produces the query:
SELECT count(*) AS 'count'
FROM `users`
WHERE ((`username` = 'alpha')
AND (`status` = 'new'))
LIMIT 1
The error message you should have been getting was:
NoMethodError: undefined method `where' for #<Sequel::SQLite::Database: ...>
If you saw this error and read it, it should have let you know that calling db.where was not right.
In addition to making this work with the native Sequel DSL, you can also always run raw sql commands in Sequel.

undefined method `user_id' for #<ActiveRecord::Relation:0x007f8da82da248>

I am error in the 2nd line of the code here, I have a column user_id in the Estate table. What am I doing wrong here ?
myestate = Estate.where(:Mgmt => current_user.Company)
#managements = User.where(:id => myestate.user_id)
where is returning an ActiveRecord::Relation object. Because where(:mgmt => current_user.company) could return 0, 1, or Many records, you have to tell the query what you'd like from it.
Try:
myestate = Estate.where(:Mgmt => current_user.Company).first
#managements = User.where(:id => myestate.user_id)
Getting familiar with AREL and how it works is highly recommended. You can find great info on the github page or the Active Record Query Guide

Null value cannot be assigned - LINQ query question

I have the following LINQ query:
DataClassesDataContext dc = new DataClassesDataContext();
var query = from contact in dc.Contacts
select new
{
ContactId = contact.ContactId,
LastName = contact.LastName,
FirstName = contact.FirstName,
Addresses = contact.Addresses,
Phones = contact.Phones,
DOB = contact.BirthDate,
LastNote = contact.Notes.Max(n => n.Created), //this line causes the error
Status = contact.ContactStatus.ContactStatusName,
EmailAddress = contact.Emails
};
The line where I get the maximum created date for the notes collection causes the following exception to be thrown:
Exception: The null value cannot be assigned to a
member with type System.DateTime which
is a non-nullable value type.
How do I write the query to allow null values into the LastNote field? The DOB field is defined as DateTime? and has not problem handling nulls.
Think I figured it out.
If I cast the maximum note value to a nullable DateTime it seems to eliminate the exception. The following change worked for me:
LastNote = (Nullable<DateTime>)contact.Notes.Max(n => n.Created)
As others have pointed out, it can also be written using the shorthand notation for a nullable DateTime as follows:
LastNote = (DateTime?) contact.Notes.Max(n => n.Created)
Rewrite that line as:
LastNote = (DateTime?) contact.Notes.Max(n => n.Created),
LastNote = contact.Notes.Max(n => (DateTime?)n.Created)
Couldn't find this on the net so i hope this helps others.
In VB is something like:
LastNote = CType(contact.Notes.Max(n => n.Created), Global.System.Nullable(Of Date))
I think...
You could do that, or you could alter your database schema so that the column 'Created' does not allow nulls.
The scenario is arising because one of the rows comes back with a null value for Created.
If the db didn't allow nulls, the scenario would never occur.

Resources