Rails: eager load related model with condition at third model - ruby-on-rails

I am very stuck on this problem:
I have next models (it's all from Redmine):
Issue (has_many :journals)
Journal (has_many :details, :class_name => "JournalDetails)
JournalDetails
I want fetch last changing of a state of a issue: date saved in Journal model but for filter only changing state I must join to JournalDetails.
Issue.eager_load(:journals).eager_load(journals: :details)
It's work but journals have all items not only changes of state - and how I can filter only changing of state without additional query I don't know
My next try:
Issue.eager_load({:journals => :details}).where("journal_details.prop_key = 'status_id'")
In this case I don't get issues which has not changes of state.

This should work:
Issue.joins(journals: :details).where(details: { prop_key: "status_id" })
Or, you can merge the scope from the details model:
class JournalDetails
scope :for_prop_key, -> (status_id) { where(prop_key: status_id )}
end
Issue.joins(journals: :details).merge(
JournalDetails.for_prop_key("status_id")
)

To fetch all issues, which have a non null prop_key in journal details:
class JournalDetails
scope :with_non_null_prop_key, -> { where("prop_key IS NOT NULL") }
end
Issue.joins(journals: :details).merge(
JournalDetails.with_non_null_prop_key("status_id")
)

Related

Active Record Scope modifies Active Record Relation. Why?

Applying a scope to a an Active Record Relation is permanently modifying the relation. Why?
company_purchases.to_sql
=> "SELECT \"purchases\".* FROM \"purchases\" WHERE \"purchases\".\"company_id\" = 17"
company_purchases.by_state("finalized").to_sql
=> "SELECT \"purchases\".* FROM \"purchases\" WHERE \"purchases\".\"company_id\" = 17 AND \"purchases\".\"state\" = 'finalized'"
company_purchases.to_sql
=> "SELECT \"purchases\".* FROM \"purchases\" WHERE \"purchases\".\"company_id\" = 17 AND \"purchases\".\"state\" = 'finalized'"
I expect the SQL to look different when called on the scope, but I don't understand why the additional where from the scope remains on the next call to company_purchases without the scope.
The scope definition
scope :by_state, ->(state) { where(state: state) }
UPDATE
This appears to be a bug with the gem Octopus, see here: https://github.com/thiagopradi/octopus/issues/455
For additional context, the Octopus bug is being introduced because of how company_purchases is composed.
company_purchases = company.purchases
# in Company model
def purchases
Product.using(shard).where(company_id: id)
end
If you default_scope than it will display on every query you make on that model. Instead use scope to avoid above problem.
This appears to be an issue with Octopus, not Active Record scopes or relations.
See: https://github.com/thiagopradi/octopus/issues/455

Rails query: get all parent records based on latest child records

An order has_many order_events.
An order_event is a record of the state of the order, e.g., pending_approval, confirmed, etc.
Changes to an order are tracked by creating order_events.
I usually get the current state of an order by doing something like: order.order_events.last.try(:state).
I would like a query to get all of the orders with a given current state, e.g., all orders where the current state is cancelable.
I initially had a scope in the OrderEvent model:
scope :cancelable, -> { where('state = ? OR state = ?', 'pending_approval', 'pending_confirmation') }
and then a scope in the Order model:
scope :with_dates_and_current_state_cancelable, -> { with_dates.joins(:order_events).merge(OrderEvent.cancelable) }
and simply used the latter for other purposes.
The problem here is that it returns all orders that are currently or have in the past satisfied the condition.
What is the best way to get all of the orders that currently satisfy the condition?
I ended up using a query like this:
scope :with_dates_and_current_state_cancelable, -> {
with_dates
.joins(:order_events)
.where('order_events.created_at = (SELECT MAX(order_events.created_at) FROM order_events WHERE order_events.order_id = orders.id)')
.where('order_events.state = ? OR order_events.state = ?', 'pending_approval', 'pending_confirmation')
.group('orders.id')
}
A bit hard to read, but it seems to work.
A classic solution here would be to use Rails enum.
Add this to your order model:
class Order
enum status: [ :pending_approval, :confirmed, etc.. ]
...
end
The status can be changed by doing the following:
# order.update! status: 0
order.pending_approval!
order.pending_approval? # => true
order.status # => "pending_approval"
No need for the order_events model.
To query all the orders that are pending approval:
Order.where(status: :pending_approval)
Edit:
Alternate solution when order_event has necessary columns.
Add a column to the order_event called archived which can either be set to 1 or 0. Set the default scope in the order_event model to this:
default_cope where(:archived => 0)
Assuming 0 is not archived.
Now, when you create a new order event set the old event to 1.
old_event = OrderEvent.find(params[:order_id])
old_event.update(archived: 1)
new_event = OrderEvent.create(...archived: 0)
Whenever you query for pending review like so:
OrderEvent.where(:status => pending_approval)
Only events that are not archived will be shown.
I think I figured out a query that might work. I didn't turn it in to ActiveRecord methods, but here it is:
SELECT t.order_id
FROM
(SELECT MAX(created_at) AS created, order_id
FROM order_events
GROUP BY order_id) as t
INNER JOIN order_events
ON t.order_id = order_events.order_id AND
t.created = order_events.created_at
WHERE order_events.state = 'whatever_state_you_want'

Rails ActiveRecord - querying on last record of relationship

I have a model Book with a has_many relationship to State.
class Book < ActiveRecord::Base
has_many :states
...
end
State sets the visibility of the book to "private", "restricted" or "public" through a name attribute. For auditing purposes, we keep a record of all state changes so to get the current state of a book I use
> book = Book.first
> book.states.last.name
> "public"
Now I need to query on all Book objects where the current state is public.
Something along the lines of:
Book.joins(:visibility_states).where(states: { state: "public"})
The problem is that the query above returns all books that are currently public, or have been public in the past. I only want it to return books that are currently "public" (i.e. book.states.last.name == "public").
I know I can do it with select but that's generating one query for each record:
Book.all.select { |b| b.states.last.name == "public" }
Is there a way to do it using ActiveRecord only?
You can use window function:
Book.joins(:visibility_states)
.where(states: { state: "public"})
.where("visibility_states.id = FIRST_VALUE(visibility_states.id)
OVER(PARTITION BY books.id ORDER BY visibility_states.created_at DESC))")
Or may be in your situation it would be better to save current state in Book model
I will do something with better performance.
If you want to save the historical state changes, is it ok. But try to avoid to introduce more complexity to your application because of this.
Why don't you add a current_state attribute in your Book model?
It will be much faster, and easier to develop.
class Book < ActiveRecord::Base
def set_new_current_state!(new_state)
self.current_state = new_state # e.g State.public
self.stats << State.create(new_state)
end
end
And your query will be just this:
Book.where(current_state: 'public')

Using state attributes to maintain old records in Rails

I want to keep old records that would be normally destroyed. For example, an user joins a project, and is kicked from it later on. I want to keep the user_project record with something that flags the record as inactive. For this I use a state attribute in each model to define the current state of each record.
Almost all my "queries" want just the "active" records, the records with state == 1, and I want to use the ActiveRecord helpers (find_by etc). I don't want to add to all the "find_by's" I use a "_and_state" to find only the records that are active.
This is what I have now:
u = UserProject.find_by_user_id_and_project_id id1, id2
This is what I will have for every query like this for all models:
u = UserProject.find_by_user_id_and_project_id_and_state id1, id2, 1
What is the most cleaner way to implement this (the state maintenance and the cleaner query code)?
create a scope in your model UserProject:
class UserProject < ActiveRecord::Base
scope :active, where(:state => 1)
end
and "filter" your queries:
u = UserProject.active.find_by_user_id_and_project_id id1, id2
if you "almost allways" query the active UserProjects only, you can define this scope as default_scope and use unscoped if you want to query all records:
class UserProject < ActiveRecord::Base
default_scope where(:state => 1)
end
u = UserProject.find_by_user_id_and_project_id id1, id2 # only active UserProjects
u = UserProject.unscoped.find_by_user_id_and_project_id id1, id2 # all states
Here's a range of soft deletion gems you may want to choose from, which offer a nice abstraction that's already been thought through and debugged:
rails3_acts_as_paranoid
acts_as_archive
paranoia
Although if this happens to be your first Rails app, I second Martin's advice of rolling your own implementation.
I tried to just add this to Martin's answer, but my edit has to be reviewed, so even though Martin's answer was great, we can improve on it a little with the idea of default scopes. A default scope is always applied to finders on the model you add them to unless you specifically turn off the default scope:
class UserProject < ActiveRecord::Base
default_scope where(:state => 1)
end
The example Martin gave then becomes:
u = UserProject.find_by_user_id_and_project_id id1, id2
In this case, even without specifying that you want state == 1, you will only get active records. If this is almost always what you want, using a default scope will ensure you don't accidentally leave off the '.active' somewhere in your code, potentially creating a hard-to-find bug.
If you specify your default scope like this:
default_scope :conditions => {:state => 1}
then newly created UserProjects will already have state set to 1 without you having to explicitly set it.
Here's more information on default scopes: http://apidock.com/rails/ActiveRecord/Base/default_scope/class
Here's how to turn them off temporarily when you need to find all records:
http://apidock.com/rails/ActiveRecord/Scoping/Default/ClassMethods/unscoped

Select the complement of a set

I am using Rails 3.0. I have two tables: Listings and Offers. A Listing has-many Offers. An offer can have accepted be true or false.
I want to select every Listing that does not have an Offer with accepted being true. I tried
Listing.joins(:offers).where('offers.accepted' => false)
However, since a Listing can have many Offers, this selects every listing that has non-accepted Offers, even if there is an accepted Offer for that Listing.
In case that isn't clear, what I want is the complement of the set:
Listing.joins(:offers).where('offers.accepted' => true)
My current temporary solution is to grab all of them and then do a filter on the array, like so:
class Listing < ActiveRecord::Base
...
def self.open
Listing.all.find_all {|l| l.open? }
end
def open?
!offers.exists?(:accepted => true)
end
end
I would prefer if the solution ran the filtering on the database side.
The first thing that comes to mind is to do essentially the same thing you're doing now, but in the database.
scope :accepted, lambda {
joins(:offers).where('offers.accepted' => true)
}
scope :open, lambda {
# take your accepted scope, but just use it to get at the "accepted" ids
relation = accepted.select("listings.id")
# then use select values to get at those initial ids
ids = connection.select_values(relation.to_sql)
# exclude the "accepted" records, or return an unchanged scope if there are none
ids.empty? ? scoped : where(arel_table[:id].not_in(ids))
}
I'm sure this could be done more cleanly using an outer join and grouping, but it's not coming to me immediately :-)

Resources