Getting a count value between many different models and associations - ruby-on-rails-4

I've been wondering what is the easiest way of getting a count value between several different models and associations.
I want to have something like this in my view
shop.receipts.articles.complaints.complaint_reviews.count
Here are my models and associations between them:
class Shop < ActiveRecord::Base
has_many :receipts
end
class Receipt < ActiveRecord::Base
has_many :articles, dependent: :destroy
belongs_to :shop
accepts_nested_attributes_for :articles, allow_destroy:true, :reject_if => :all_blank
end
class Article < ActiveRecord::Base
belongs_to :receipt
has_one :complaint
end
class Complaint < ActiveRecord::Base
belongs_to :article
has_many :complaint_reviews
end
class ComplaintReview < ActiveRecord::Base
belongs_to :complaint
end

I'm inferring that you want the count of all complaint_reviews that are associated with a particular shop.
In that case, the following is what you need:
shop = # get shop according to your criteria
ComplaintReview.
joins(complaint: {article: {receipt: :shop}}).
where(shops: {id: shop.id}).
count
I suppose you could save the shop joins, by applying the condition on the shop_id column of receipts; like so:
ComplaintReview.
joins(complaint: {article: :receipt}).
where(receipts: {shop_id: shop.id}).
count
Result should be the same for both if all receipts have a shop associated. But I'd opt for the first method.
The thing to keep in mind here is to 'start' with the model of which you ultimately want the count of.
Also, had there been any one-to-many relationships, you would have grouped the results by "complain_reviews.id" and then performed the count.

Ok so thanks to the code above I managed to come up with a working solution:
#shops_controller.rb:
def show
#count = ComplaintReview.
joins(complaint: {article: {receipt: :shop}}).
where(shops: {id: #shop.id}).
count
respond_with(#shop)
end
#shops/show.html.erb:
<%= #count %>
Thanks a lot for the help.

Related

Rails: multiple associations query

I have associations like this: Profession -> orders -> profile -> location
Class Profession < ActiveRecord::Base
has_many: orders
end
Class Order < ActiveRecord::Base
has_one :profession
belongs_to :profile
end
Class Profile < ActiveRecord::Base
has_one :location
has_many :orders
end
Class Location < ActiveRecord::Base
belong_to :profile
end
And I need to find a professions which are in the location.city.
For example I try this:
Profession.joins(:orders).where(orders: {profile: {location: {city: "Simferopol"}}})
Is this possible?
Thanks.
You might consider an association using through:
class Profession < ActiveRecord::Base
has_many :orders
has_many :profiles, through: :orders
end
This may make life easier for you allowing you to call:
Profession.profiles
This will return all profiles for a given state. It just seems less messy to me. As you still need to reach the location associated with a profile I am sure there is a more optimal solution, but I believe this approach is better than the proposed:
Profession.joins(:orders).where(orders: {profile: {location: {city: "Simferopol"}}})

Active Record Query for belongs_to association

I am using rails 4.2. and have the following structure:
class User < ActiveRecord::Base
has_many :records
end
class Record < ActiveRecord::Base
belongs_to :user
belongs_to :drop
end
class Drop < ActiveRecord::Base
has_many :records
end
I want to get all the records for a specific user (e.g. Record.where(user_id: current_user.id) but include the drop for each record. I can't get the query right. Can you help?
I worked it out. To join the tables you need a "select" clause and specify which columns you want. The query was then:
current_user.drops.joins(:records).select("drops.*, records.*")

use of includes or left outer joins for complex nested associations

I have four models
class Company < ActiveRecord::Base
has_many :share_types
belongs_to :user
end
class ShareType < ActiveRecord::Base
has_many :shares
belongs_to :company
end
class Share < ActiveRecord::Base
belongs_to :user
belongs_to :share_type
end
class User < ActiveRecord:Base
has_many :companies
has_many :shares
end
Now list of all companies where company is owned by current_user or user have shares in a company something like this.
Company.joins(share_types:[:shares]).where("shares.user_id=? OR companies.user_id=?", #user.id, #user.id)
but with left outer join another I do not know how to use includes with or conditions another hint is
Company.includes(share_types:[:shares]).where(shares:{user_id: #user.id} OR companies:{user_id: 1})
How can I do that.
I am able to get my expected result with the help of references. Here is my query just posting to help others.
Company.includes(share_types:[:shares]).where("shares.user_id=? OR companies.user_id=?", 1,1).references(:shares)
its working thanks to The Rails 4 Way by Obie Fernandez

How to do a Polymorphic model association with another model

I have two basic models:
class Case < ActiveRecord::Base
has_many :contacts
end
class Contact < ActiveRecord::Base
belongs_to :case
belongs_to :contactable, :polymorphic => true, :foreign_key => :contactable_id
end
I also have quite a few models that are "sub types" of the Contact model:
class Attorney < ActiveRecord::Base
has_one :contact, as: :contactable, dependent: :destroy
accepts_nested_attributes_for :contact
end
class Client < ActiveRecord::Base
has_one :contact, as: :contactable, dependent: :destroy
accepts_nested_attributes_for :contact
end
I used polymorphic associations instead of STI because I don't want one table to store all the fields, which can get a little slow and overwhelming.
I am wondering if the has_many :contacts line from the Case model is correct. I try to use it in my console, but it doesn't really work the way I expected. Am I missing something?
I basically want an association where a Case can have many Contacts and a contact can belong to many cases. The contact can be of any type (Attorney or Client or Contact by itself). I was hoping it was as easy as case has_many :contacts

Add items to a has_many relation on creation

I'm trying to make a has_many relation work for object to be created.
It is a simple case and despite many efforts and researches through the web, I cannot find why my code is not working.
I have the following classes (note: some variables use French names):
class Comptes::Category < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
accepts_nested_attributes_for :categorizations
has_many :transactions, through: :categorizations
validates :nom, presence: true, uniqueness: true
end
class Comptes::Transaction < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
accepts_nested_attributes_for :categorizations
has_many :categories, through: :categorizations
... # some validations
end
class Comptes::Categorization < ActiveRecord::Base
belongs_to :transaction
belongs_to :category
validates :transaction, presence: true
validates :category, presence: true
end
Category and Transaction are the basic models and Categorization is dedicated to the association (this is a basic account - transaction system).
What I can do is create a transaction and a category then fill transaction.categories with the category (transaction has thus an id).
What I cannot do is:
transaction = Comptes::Transaction.new ...
category = Comptes::Category.first
transaction.categories << category
# OR
transaction.categorizations.build category: category
# OR
# use categorizations_attributes in and accepts_nested_attributes_for.
Thank you very much for any help
Edit: this is done in rails 4.0.0
And I found that the issue was coming from the validation in Comptes::Categorization.
This prevents creation of new categorizations if the transaction or category does not exist yet.
Update (18/08/2014): the issue is coming from the validation in Categorizations, which prevent from creating the association without existing transaction and category. This may be an issue in rails 4.0.0. To see...
Transaction class is not under the module Comptes. Therefore, when you do has_many :categorizations or has_many :categories in it, the corresponding models are inferred as Categorization and Category instead of Comptes::Categorization and Comptes::Category.
To resolve this, you need to specify the class_name option of the association because the name of the model can't be inferred from the association name.
Update the class Transaction as below:
class Transaction < ActiveRecord::Base
has_many :categorizations, class_name: "Comptes::Categorization" , dependent: :destroy
accepts_nested_attributes_for :categorizations
has_many :categories, through: :categorizations, class_name: "Comptes::Category"
end