Exposing associations of a has_many -> has_many through the parent? - ruby-on-rails

If a user has many things and a thing has many stats, it seems like there's only way Rails-y way to expose the stats through the user.
class User < ActiveRecord::Base
has_many :things do
def stats
Stat.where(thing_id: proxy_association.owner.things_id)
end
end
end
class Thing < ActiveRecord::Base
belongs_to :user
has_many :stats
end
class Stat < ActiveRecord::Base
belongs_to :thing
has_one :user, through: :thing
end
User.first.things.stats == Stat.where(thing_id: User.first.thing_ids)
I'm trying to determine whether there are any other options... Some people on my team complain that this doesn't feel natural. I feel like this is the most natural expression of the relationship you could devise.
Does anyone have a better suggestion? I'll say, I've tried instance methods and they don't smell right.

I might use a has_many :stats, :through => :things in the User class.
Check out this: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Related

ActiveRecord: has_many choices limited to has_many of another model

I would like to achieve something as follows where PersonSubject has many topics, but the choices of these topics are limited to the the selection of topics through another model (ie: through the associated subject):
class Topic < ApplicationRecord
belongs_to :subject
end
class Subject < ApplicationRecord
has_many :topics
end
class PersonSubject < ApplicationRecord
belongs_to :person
belongs_to :subject
has_many :topics # where the choices are limited to the subject.skills
end
I would then like if any person_subject.subject.topics are deleted (or association removed), it would automatically update the person_subject.topics to no longer "point" to the Topic(s) that were deleted.
Is this possible?
You can use a lambda to put arbitrary filters on an association. See What is the equivalent of the has_many 'conditions' option in Rails 4?
has_many :topics, -> { where(skill: subject.skills) }
I don't know that this is exact code will work without seeing your schema (what is the data type of subject.skills, and how do you join this with topic?). But hopefully this gets you on the right track
edit
in response to your comment, I think
has_many :topics, through: :skills
would work

How to implement ancestry for this specific situation

We have a Real-Estate app in which the User can be a Renter or Landlord(Owner). Renters can search for specific houses listed by the Owners. Renters can also add other persons(friends or acquaintances who are staying with that specific renter). In the app we treat them as Coapplicants.
Models
# user.rb
class User < ActiveRecord::Base
has_one :renter
has_one :owner
end
# renter.rb
class Renter < ActiveRecord::Base
belongs_to :user
has_many :coapplicants
end
# coapplicant.rb
class Coapplicant < ActiveRecord::Base
belongs_to :renter
end
Now as to increase the number of users for the app,we implemented a mailing system which sends an Welcome Mail(when the Renter adds a Coapplicant) to signup as a User.And that Coapplicant can choose to be Renter and can add many Coapplicants too. And the process goes on again resulting in increasing the users.
It's like a tree structure and now I want to set-up a perfect database relations(associations) to track the users flowing in and through which renter/coapplicant they are coming.
Now the Current Model structure(not yet developed) looks like this
# user.rb
class User < ActiveRecord::Base
has_one :renter
has_one :owner
end
# renter.rb
class Renter < ActiveRecord::Base
belongs_to :user
has_many :coapplicants
has_many :coapp_renters,
:through => :coapplicants
has_many :inverse_coapplicants,
:class_name => "Coapplicant",
:foreign_key => "coapp_renter_id"
has_many :inverse_coapp_renters,
:through => :inverse_coapplicants,
:source => :renter
end
# coapplicant.rb
class Coapplicant < ActiveRecord::Base
belongs_to :renter
belongs_to :coapp_renter,
:class_name => "Renter"
end
I guess i messed up things a bit. Which database-relationships(associations) would be the best for my current situation.
Can someone throw some light on this please.I'm thinking about using the ancestry gem but how to implement to my current situation.
I've found that sometimes even a small change in perspective when designing your associations can make them flow a lot more naturally.
You have focused exclusively on person entities; User.find(1).renter for example isn't very intuitive, since both models depict essentially the same person.
Instead of trying to model what people are, I would try to model what they have. In this case, instead of a User having a Renter, let them have many Rentals:
class User < ActiveRecord::Base
has_many :rentals,
foreign_key: 'renter_id'
end
class Rental
belongs_to :renter,
class_name: 'User'
belongs_to :property
end
I assume here that you have a model Property that stands for what is being rented - leave that out if it doesn't exist.
It's the same thing for owners. A User becomes an owner just by having Ownerships:
class User < ActiveRecord::Base
has_many :ownerships,
foreign_key: 'owner_id'
end
class Ownership
belongs_to :owner,
class_name: 'User'
belongs_to :property
end
A co-application is slightly different in that it belongs to a Rental:
class CoApplication
belongs_to :co_applicant,
class_name: 'User'
belongs_to :rental
end
class Rental
has_many :co_applications
end
class User < ActiveRecord::Base
has_many :co_applications,
foreign_key: 'co_applicant_id'
has_many :received_co_applications,
through: :rentals,
source: :co_applications
end
Now your Users can be owners, renters, co-applicants - all at the same time. And these associations allow you to capture everything that happened - who signed on whom through what is just a matter of chronological order.
From here on it's a matter of nesting your has_many :through associations to get whatever you want.
Want to know the properties a landlord owns?
has_many :owned_properties,
through: :ownerships,
source: :property
The rentals to her properties?
has_many :leases,
through: :owned_properties,
source: :rentals
The people who rented her properties?
has_many :renters,
through: :leases,
source: :renter
Same thing with co-applications. Want to know who co-applied with a user?
has_many :co_applicants,
through: :received_co_applications,
source: :co_applicant
I would refactor your code and make the co-applicants just a renter that is a child of another renter
in your renter model you have to add a "parent_id" to know whom the co-applicants belongs to.
now in your model you can do something like
#renter.rb
class Renter < ActiveRecord::Base
belongs_to :user
has_many :children, :class_name => "Renter"
belongs_to :parent, :class_name => "Renter"
end
# Example calls
Renter.first.children
Renter.first.parent
I hope this helps
Create a table called Relationship (or something) with two foreign_ids concerning what you want the User and Renter to be able to do with one another (example to be able to "Follow" one another => Follower_id and Following_id). Define methods in your Models related to those ids and then call those methods in your views to display the relations.

Rails multiple association types

Can you have a has_many belongs_to relationship AND a has_many :through relationship without any method call conflicts?
For example, what would user.hacks return - the hacks that the user posted, or the hacks that the user marked as favorites?
I need to be able to access both results.
class User < ActiveRecord::Base
has_many :hacks, through: :favorites
has_many :hacks
end
class Hack < ActiveRecord::Base
has_many :hacks, through: :favorites
belongs_to :users
end
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :hack
end
The has_many defines the methods depending on the relationship name.
This means, that if you are defining a relationship several times with the same name but different options, the last definition will override the methods of the previous definition calls.
So you can't define them with the same name.
If you need to access to both, hacks and favorite hacks, you have to create the relationships as follows
class User < ActiveRecord::Base
has_many :hacks
has_many :favorites
has_many :favorited_hacks, through: :favorites, source: :hack
end
I'm not sure what it will return, try it in the console.
However i would something like that in the user class (not tested, but you can look on how to alias relations):
has_many :favorite_hacks, through: :favorites, class: :hacks
There seems to be a typo in Hack.
On another note, the way you do it seems strange to me. The user hack relation seems like ownership, and the user - fav seems like bookmarking.
If all you want is to get a list of all favourite hacks (and all hacks belong to the user), then I think it would be a much better idea to model this behaviour like so:
class User < ActiveRecord::Base
has_many :hacks
end
class Hack < ActiveRecord::Base
belongs_to :user
scope :favorite, -> { where(favorite: true) }
end
and simply have a favorite attribute on your Hack model. Then you could find the favorites by invoking user.hacks.favorite.

Use where on has_many :through to find objects with 2 certain child object from different classes (Rails 4)

What I want to do is to get all the
My model:
class User < ActiveRecord::Base
has_many :classes
has_many :professors, :through=>:classes
has_many :cars
has_many :carmodels, :through=>:cars
end
class Professor < ActiveRecord::Base
has_many :classes
has_many :users, :through=>:classes
end
class Class < ActiveRecord::Base
belongs_to :user
belongs_to: professor
end
class Car < ActiveRecord::Base
belongs_to :user
belongs_to :carmodel
end
class Carmodel
has_many :cars
has_many :users, through=>:cars
end
what I want to do is, given a certain Car and Professor, to find all users which contain them.
for example
u1=carmodel.users
u2=professor.users
result=[]
u1.each do |us|
if u2.include? us
result.push us
end
end
Of course this is just an example... I would like to keep working with ActiveRecords(avoid turning it to an array) and, of course, a more optimal solution... I can't seem to find any.
You need to do something like this:
User.joins(:carmodels).joins(:professors)
Thanks for the previous answer! Here is the resulting code:
carmodel #Variable for the wanted carmodel
professor #Variable for the wanted professor
result=User.joins(:carmodels).joins(:professors).where(carmodel:{id:carmodel.id},professors:{id:professor.id})
Thanks again!

Like/Dislike style Voting Database in Rails

I’m creating a voting feature for our website in the style of YouTube “Likes” and “Dislikes” and Digg using Ruby on Rails 3. I have having trouble coming up with the right scheme.
I have three models, Users, Topics, and Votes. Each User will make one vote “Like” or “Dislike” for one Topic. Like these sites, Users can Vote on a Topic, but they can also create new Topics. I’d like to be able to not only view all of a User’s Votes, but also both the Topics they have created and the Topics they have voted on. I am trying to build this on our own and decide how best to setup the database to handle this process.
My first idea was to use :has_many and belongs_to exclusively like so…
class User < ActiveRecord::Base
has_many :votes
has_many :topics
class Topic < ActiveRecord::Base
has_many :votes
belongs_to :users
class Vote < ActiveRecord::Base
belongs_to :topics
belongs_to :users
boolean choice #tracks whether the User chooses Like or Dislike
But it became evident that this might not be the best way to do this. I began to think the best method would be to use a :has_many :through association like...
class User < ActiveRecord::Base
has_many :votes, :through => :topics
But I’m not sure. Any ideas on how best to set something like this up?
I think your initial setup is good but it can be further improved upon to better support what you want to accomplish. Perhaps like this:
class User < ActiveRecord::Base
has_many :votes
has_many :topics
#Lists all topics the user has voted on
has_many :voted_topics, :through => :votes, :source => :topic
#Lists all votes for the users topics
has_many :topic_votes, :through => :topics, :source => :votes
end
class Topic < ActiveRecord::Base
has_many :votes
belongs_to :user
end
class Vote < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end

Resources