Ruby on Rails autosave associations - ruby-on-rails

I have three associated classes in Rails v. 3.2.15, with Ruby 2.1.1, and a join-table class between two of them:
class Grandarent < ActiveRecord::Base
has_many :parents, autosave: true
end
class Parent
belongs_to :grandparent
has_many :children, :through => :parent_children, autosave: true
end
class ParentChild
belongs_to :parent
belongs_to :child
end
class Child
has_many :parent_children
has_many :parents, :through => :parent_children
end
If I execute the following, then changes to child are not saved:
gp = Grandparent.find(1)
gp.parents.first.children.first.first_name = "Bob"
gp.save
gp.parents.first.children.first.first_name ## -> Whatever name was to begin with (i.e. NOT Bob)
But if I force Rails to evaluate and return data from each connection, then the save is successful
gp = Grandparent.find(1)
gp.parents
gp.parents.first
gp.parents.first.children
gp.parents.first.children.first
gp.parents.first.children.first.first_name = "Bob"
gp.save
gp.parents.first.children.first.first_name ## -> "Bob"
If I subsequently execute gp = Grandparent.find(1) again, then I've reset the whole thing, and have to force the evaluation of associations again.
Is this intentional behavior, or have I done something wrong? Do I need to hang an autosave on the join table connections as well as (or instead of) the has_many :through connection?
From the documentation, I see that "loaded" members will be saved. Is this what is necessary to load them? Can someone define exactly what "loaded" is, and how to achieve that state?

It is happening because gp.parents caches the parents into a results Array, then parents.first is actually calling Array.first. However, gp.parents.first performs a query with LIMIT 1 every time, and so returns a new object every time.
You can confirm like so:
gp.parents.first.object_id # performs new query (LIMIT 1)
=> 1
gp.parents.first.object_id # performs new query (LIMIT 1)
=> 2
gp.parents # performs and caches query for parents
gp.parents.first.object_id # returns first result from parents array
=> 1
gp.parents.first.object_id # returns first result from parents array
=> 1
You can chain an update with your query like so:
gp.parents.first.children.first.update_attributes(first_name: "Bob")

Related

Active Record: Remove element from PostgreSQL array

Assume there's an active record model called Job which has an array column follower_ids. I have already created a scope which allows to fetch all jobs followed by a user:
# Returns all jobs followed by the specified user id
def self.followed_by(user_id)
where(
Arel::Nodes::InfixOperation.new(
'#>',
Job.arel_table[:follower_ids],
Arel.sql("ARRAY[#{user_id}]::bigint[]")
)
)
end
# Retrieve all jobs followed by user with id=1
Job.followed_by(1)
Is there a way to remove specific elements from the follower_ids column using the database (i.e., not looping through the active record objects and manually calling delete/save for each of them)?
For instance, it'd be nice to do something like Job.followed_by(1).remove_follower(1) to remove user with id=1 from all those jobs' follower_ids with just one query.
I ended using the PostgreSQL array_remove function, which allows to remove a value from an array as follows:
user_id = 1
update_query = <<~SQL
follower_ids = ARRAY_REMOVE(follower_ids, :user_id::bigint),
SQL
sql = ActiveRecord::Base.sanitize_sql([update_query, { user_id: user_id }])
Job.followed_by(user_id).update_all(sql)
I think this is really a XY problem caused by the fact that you are using an array column where you should be using a join table.
The main reasons you don't want to use an array are:
If user is deleted you would have to update every row in the jobs table instead of just removing rows in the join table with a cascade or the delete callback.
No referential integrity.
Horrible unreadable queries. Its really just a marginal step up from a comma separated string.
Joins are not really that expensive. "Premature optimzation is the root of all evil".
You can't use ActiveRecord associations with array columns.
Create the join model with rails g model following user:references job:references. And then setup the assocations:
class Job < ApplicationRecord
has_many :followings
has_many :followers,
through: :followings,
source: :user
end
class User < ApplicationRecord
has_many :followings
has_many :followed_jobs,
source: :job,
through: :followings,
class_name: 'Job'
end
To select jobs followed by a user you just do a inner join:
user.followed_jobs
To get jobs that are not followed you do an outer join on followings where the user id is nil or not equal to user_id.
fui = Following.arel_table[:user_id]
Job.left_joins(:followings)
.where(fui.eq(nil).or(fui.not_eq(1)))
If you want to unfollow a job you just remove the row from followings:
Following.find_by(job: job, user: user).destroy
# or
job.followings.find_by(user: user).destroy
# or
user.followings.find_by(job: job).destroy
You can automatically do this with the when the job or user is destroyed with the dependent: option.

Mongoid: How do I query for all object where the number of has_many object are > 0

I have a Gift model:
class Gift
include Mongoid::Document
include Mongoid::Timestamps
has_many :gift_units, :inverse_of => :gift
end
And I have a GiftUnit model:
class GiftUnit
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :gift, :inverse_of => :gift_units
end
Some of my gifts have gift_units, but others have not. How do I query for all the gifts where gift.gift_units.size > 0?
Fyi: Gift.where(:gift_units.exists => true) does not return anything.
That has_many is an assertion about the structure of GiftUnit, not the structure of Gift. When you say something like this:
class A
has_many :bs
end
you are saying that instance of B have an a_id field whose values are ids for A instances, i.e. for any b which is an instance of B, you can say A.find(b.a_id) and get an instance of A back.
MongoDB doesn't support JOINs so anything in a Gift.where has to be a Gift field. But your Gifts have no gift_units field so Gift.where(:gift_units.exists => true) will never give you anything.
You could probably use aggregation through GiftUnit to find what you're looking for but a counter cache on your belongs_to relation should work better. If you had this:
belongs_to :gift, :inverse_of => :gift_units, :counter_cache => true
then you would get a gift_units_count field in your Gifts and you could:
Gift.where(:gift_units_count.gt => 0)
to find what you're looking for. You might have to add the gift_units_count field to Gift yourself, I'm finding conflicting information about this but I'm told (by a reliable source) in the comments that Mongoid4 creates the field itself.
If you're adding the counter cache to existing documents then you'll have to use update_counters to initialize them before you can query on them.
I tried to find a solution for this problem several times already and always gave up. I just got an idea how this can be easily mimicked. It might not be a very scalable way, but it works for limited object counts. The key to this is a sentence from this documentation where it says:
Class methods on models that return criteria objects are also treated like scopes, and can be chained as well.
So, get this done, you can define a class function like so:
def self.with_units
ids = Gift.all.select{|g| g.gift_units.count > 0}.map(&:id)
Gift.where(:id.in => ids)
end
The advantage is, that you can do all kinds of queries on the associated (GiftUnits) model and return those Gift instances, where those queries are satisfied (which was the case for me) and most importantly you can chain further queries like so:
Gift.with_units.where(:some_field => some_value)

ActiveRecord: Accessing owner association after building record

Using Rails 2.3.14, I'm looking for way to access the owner of an ActiveRecord object after it was build (but before save) to get some values from the owner. Seems to be simple, but my approach always fires an unnecessary database query.
Example:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
def after_initialize
self.some_value = parent.some_value
# This fires an additional database query to get the parent
end
end
parent = Parent.find(1)
# SELECT * FROM `parents` WHERE (`parents`.`id` = 1)
child = parent.children.build
# Same SELECT query is fired again, but of course not needed
I'm looking for a way to access the association object (here: parent) without doing an additional database access. How can this be done?
In Rails 3, there's a new option, :inverse_of, for belongs_to/has_many to do this, but not in Rails 2. Maybe you have to implement similar function by yourself.

How to make ActiveRecord execute SQL to load association when the parent model object is not persisted yet?

I am doing things in a non-standard way. I am assigning IDS on object creation.
So, during before_save callbacks, which access a parent model's child association collections, I have this issue, where ActiveRecord won't actually execute the SQL to lookup the child association.
I can get the associated objects by doing a find on their class, as shown below, but is there any way to force the collection association methods to actually run the query and fetch the children when the parent itself has not been saved yet?
class Project < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :project
end
3.times do
Task.create(:project_id => 1)
end
Tasks.where(:project_id => 1).count
# 3
tasks = Tasks.where(:project_id => 1)
# SELECT * FROM tasks WHERE project_id = 1;
p = Project.new(:id => 1)
p.tasks # nil
# no SQL query executed
There is no SQL executed because you haven't saved your Project record yet. Try changing Project.new(:id => 1) to Project.create!(:id => 1) and then query your tasks.
In other words, your project doesn't exist, so why would it look for tasks underneath it?

Including an association if it exists in a rails query

Update: This may be something that just isn't doable. See this
TLDR: How do you conditionally load an association (say, only load the association for the current user) while also including records that don't have that association at all?
Rails 3.1, here's roughly the model I'm working with.
class User
has_many :subscriptions
has_many :collections, :through => :subscriptions
end
class Collection
has_many :things
end
class Thing
has_many :user_thing_states, :dependent => :destroy
belongs_to :collection
end
class Subscription
belongs_to :user
belongs_to :collection
end
class UserThingState
belongs_to :user
belongs_to :thing
end
There exist many collections which have many things. Users subscribe to many collections and thereby they subscribe to many things. Users have a state with respect to things, but not necessarily, and are still subscribed to things even if they don't happen to have a state for them. When a user subscribes to a collection and its associated things, a state is not generated for every single thing (which could be in the hundreds). Instead, states are generated when a user first interacts with a given thing. Now, the problem: I want to select all of the user's subscribed things while loading the user's state for each thing where the state exists.
Conceptually this isn't that hard. For reference, the SQL that would get me the data needed for this is:
SELECT things.*, user_thing_states.* FROM things
# Next line gets me all things subscribed to
INNER JOIN subscriptions as subs ON things.collection_id = subs.collection_id AND subs.user_id = :user_id
# Next line pulls in the state data for the user
LEFT JOIN user_thing_states as uts ON things.id = uts.thing_id AND uqs.user_id = :user_id
I just don't know how to piece it together in rails. What happens in the Thing class? Thing.includes(:user_thing_states) would load all states for all users and that looks like the only tool. I need something like this but am not sure how (or if it's possible):
class Thing
has_many :user_thing_states
delegates :some_state_property, :to => :state, :allow_nil => true
def state
# There should be only one user_thing_state if the include is correct, state method to access it.
self.user_thing_states.first
end
end
I need something like:
Thing.includes(:user_question_states, **where 'user_question_state.user_id => :user_id**).by_collections(user.collections)
Then I can do
things = User.things_subscribed_to
things.first.some_state_property # the property of the state loaded for the current user.
You don't need to do anything.
class User
has_many :user_thing_states
has_many :things, :through => :user_thing_states
end
# All Users w/ Things eager loaded through States association
User.all.includes(:things)
# Lookup specific user, Load all States w/ Things (if they exist for that user)
user = User.find_by_login 'bob'
user.user_thing_states.all(:include => :things)
Using includes() for this already loads up the associated object if they exist.
There's no need to do any filtering or add extra behavior for the Users who don't have an associated object.
Just ran into this issue ourselves, and my coworker pointed out that Rails 6 seems to include support for this now: https://github.com/rails/rails/pull/32655
*Nope, didn't solve it :( Here's a treatment of the specific issue I seem to have hit.
Think I've got it, easier than expected:
class Thing
has_many :user_thing_states
delegates :some_state_property, :to => :state, :allow_nil => true
scope :with_user_state, lambda { |user|
includes(:user_thing_states).where('user_thing_states.user_id = :user_id
OR user_thing_states.user_id IS NULL',
{:user_id => user.id}) }
def state
self.user_thing_states.first
end
end
So:
Thing.with_user_state(current_user).all
Will load all Things and each thing will have only one user_question_state accessible via state, and won't exclude Things with no state.
Answering my own question twice... bit awkward but anyway.
Rails doesn't seem to let you specify additional conditions for an includes() statement. If it did, my previous answer would work - you could put an additional condition on the includes() statement that would let the where conditions work correctly. To solve this we'd need to get includes() to use something like the following SQL (Getting the 'AND' condition is the problem):
LEFT JOIN user_thing_states as uts ON things.id = uts.thing_id AND uqs.user_id = :user_id
I'm resorting to this for now which is a bit awful.
class User
...
def subscribed_things
self.subscribed_things_with_state + self.subscribed_things_with_no_state
end
def subscribed_things_with_state
self.things.includes(:user_thing_states).by_subscribed_collections(self).all
end
def subscribed_things_with_no_state
Thing.with_no_state().by_subscribed_collections(self).all
end
end

Resources