active record joins with distinct record - ruby

I have an Event model with multiple time slots(on and from attributes both are datetime)
I need to get distinct events based on some condition that is applied on the time slot model through joins and have is sorted in some order.
I tried a few approaches but it just works when i order on the event attribute and not on the time slot attribute.
Event.joins(:time_slots).order('time_slots.from asc').distinct
throws InvalidColumnReference error
Event.joins(:time_slots).order('events.id asc').distinct
works
How can I make the former query work?

I had to use Event.includes instead of Event.joins, and it actually worked as expected.

Related

Sorting Issue After Table Render in Laravel DataTables as a Service Implementation

I have implemented laravel dataTable as a service.
The initial two columns are actual id and names so, I am able to sort it asc/desc after the table renders.
But the next few columns renders after performing few calculations, i.e. these values are not fetched directly from any column rather it is processed.
I am unable to sort these columns where calculations were performed, and I get this error. And I know it is looking for that particular column for eg outstanding_amount which I don't have in the DB, rather it is a calculated amount from two or more columns that are in some other tables.
Any Suggestions on how to overcome this issue?
It looks like you're trying to sort by values that aren't columns, but calculated values.
So the main issue here is to give Eloquent/MySql the data it needs to provide the sorting.
// You might need to do some joins first
->addSelect(DB::raw('your_calc as outstanding_amount'))
->orderBy('outstanding_amount') // asc can be omitted as this is the default
// Anternative: you don't need the value sorted by
// Don't forget any joins you might need
->orderByRaw('your_calc_for_outstanding_amount ASC')
For SQL functions it'll work as follow
->addSelect(DB::raw('COUNT(products.id) as product_count'));
->orderByRaw(DB::raw('COUNT(products.id)'),'DESC');

Laravel - find offset of record in mysql results

I have a MySQL table of records with several fields.
These records are shown and updated live in the browser. They are displayed in an order choosen by the user, with optional filters also choosen by the user.
Sometimes a change is made to one of the records, and it may affect the order for a given user.
In order to position the message correctly in the list, I need to find where its new offset falls after the change to the record. Basically, I need to get the "id" for the record that now comes before it in the MySQL results, so that I can use Javascript on the client side to reposition the record on the screen.
In raw SQL, I'd do something like this:
SET #rank=0;
SELECT rank
FROM
(SELECT #rank:=#rank+1 AS rank,
subQuery.id AS innerQuery,
FROM ...{rest of custom query here}... as subQuery)
AS outerQuery WHERE outerQuery.innerQuery={ID TO FIND};
Then I can just subtract 1 from the resulting rank, and find the ID of the question that comes before the record in question.
Is this kind of query possible with Laravel's query builder? Or is there a better strategy than what I've come up with here to accomplish the same task?
EDIT: There are a lot of records. So if possible I'd like to avoid loading all the records into memory to find the offset of the record. They are originally loaded on the screen in an "infinite scroll" type method, since it would be too much to load all of them at once.

How to use calculated fields in my LightSwitch Query?

in my lightswitch application im trying to create a Customers Screen for customers who have balance value, and my balance value is a Calculated Field in the Customer Entity
when i tried to put the logic in the Process Query Event Like This
query =( from i in query
where(i.Balance>0)
select i );
i get an exception .. what is the best way to handle these kind of situations ??
i saw an answer here but i didn't know how to implement it exactly i need a sample code for it can anyone help me ??
thanks in advance
The query will be executed by the data provider, which doesn't know about calculated fields. What you can do is to filter what you want via LINQ, referring to the actual fields, not the calculated ones.
For example, let's say Balance is your calculated field, that you defined as Credit - Debit (which are normal fields). You want your query to return the rows where Balance > 0. This is how you'd write the query (in the PreprocessQuery event, note there is no ProcessQuery event):
partial void TestQuery_PreprocessQuery(ref IQueryable<Customer> query)
{
query = (
from c in query
where ((c.Credit - c.Debit) > 0)
select c);
}
Another theoretical way of solving the problem would be setting a filter in the Executed event handler. However, for whatever the reason, when I do it, the filter is not applied to the screen. But even if this method would work, still you'd be filtering on the client side, which might not be what you want.
I'm actually looking for a solution to this problem
(unfortunately I can't just include the calculation from the calculated field, because my calculation uses another calculated field which uses recursion)
A couple of pointers I thought you might find helpful:
#julio.g - for the Executed event handler, the "result" parameter is an IEnumerable parameter (as opposed to the PreProcess_Query event handler, where the "query" parameter is a ref IEnumerable) so any changes you make to the "result" will only be local to that method
#3oon - afaik, SQL Views are not supported in LightSwitch. The best option I've come across so far is to create a WCF RIA Service based on a Stored Procedure, then adding it as a datasource.
This blog post should help get you started.
http://tejana.wordpress.com/2010/12/09/microsoft-lightswitch-and-stored-procedures-using-wcf-ria-services/
Hope that helps!

iReports Grouping Bug - Multiple Occurrences?

I'm am getting irritated with iReports. Problem is that I have a data set returning data for multiple customers and I want to use the "Group Expression" against the customer ID and have the report lay out the Detail Tabs per customer.
I'm finding that, seeming randomly, where there is more that one data row for a customer iReports will generate two or more groupings (Sometimes it does what I expect and group all the customer data together), the field IDing the customer is the same and doesn't change.
Has anyone seen this before? To be honest I can't believe it is actually a bug, but something I've missed. Just much searching as yet to find a suitable result.
I think this is a data sorting problem.
The quote from iReport Ultimate Guide:
JasperReports groups records by evaluating the group expression. Every
time the expression's value changes, a new group instance is created.
The engine does not perform any record sorting (if not explicitly
requested), so when we define groups we should always take care of the
records sorting. That is, if we want to group a set of addresses by
country, the records we select for the report should already by
ordered by country. It is simple to sort data when using an SQL query
by using the ORDER BY clause. When this is not possible (that is, when
obtaining the records from an XML document), we can request that
JasperReports sort the data for us. This can be done using the sort
options available in the query window
You can sort data in these ways:
in case using of Database jdbc connection datasource type you can add ORDER BY customerId clause to the report's query, where customerId - column name of field with customer id
in case using of File csv connection or something like this you can organize data sorting by adding sortField property for field to the report's template (jrxml file):
<jasperReport ...>
...
<field name="customerId" class="java.lang.String"/>
<sortField name="customerId"/>
SQL Statement has ORDER BY?
iReport group is grouped by customer_id?

Core Data - Sorting results conditionally on values from a to-many-relationship

Hello I have an app with an Event entity that has a to-many-relationship to a Date entity that contains MULTIPLE startDates and endDates for each event.
In my list view I need to sort the events by the next available startDate (or endDate) from the to-many-relationship.
First I created a transient property in the Date entity that made all the necessary calculations (comparing to present date etc) but then quickly realized that
you cannot sort the fetchedResultsController using a transient property.
I cannot make the calculations at the time the start and end dates are created, because there is more than one startDate and endDate for each event and which ones to use
can only be determined on demand by comparing them to the present date.
Any guidance on which way to go with this would be greatly appreciated.
You might need to go about this backwards.
The simplest solution would be to fetch Date objects that fall into the needed range and then display the Event objects they relate to.
Otherwise, you will have to use a SUBQUERY in your predicate.

Resources