Active Record Query for belongs_to association - ruby-on-rails-4

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.*")

Related

How to access parameter in a join table in many to many assotiation

I have 2 models which are connected as many-to-many via third model:
class User < ActiveRecord::Base
has_and_belongs_to_many :workspaces
end
class Workspace < ActiveRecord::Base
validates :title, presence: true
has_and_belongs_to_many :users
end
class UserWorkspace < ActiveRecord::Base
belongs_to :user
belongs_to :workspace
enum role: [:user, :admin]
end
Unfortunately I can not find out how to access the parameter role for UserWorkspace. for example, #workspace.user.last.role does not work. Please could you help?

ActiveRecord::UnknownAttributeError: unknown attribute 'article_id' for Tagging

I am work on a Blogger Rails App from section I3 :
http://tutorials.jumpstartlab.com/projects/blogger.html#blogger-2
I am getting an error when running the console and attempting to run:
a.tags.create name: "tag1"
After I run:
a = Article.first
tagging.rb file:
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :articles
end
article.rb file:
class Article < ActiveRecord::Base
has_many :comments
has_many :taggings
has_many :tags, through: :taggings
end
tag.rb file:
class Tag < ActiveRecord::Base
has_many :taggings
has_many :articles, through: :taggings
end
I tried adding has_many :article_id to the tagging class, raked the db:migration and ran it again and it came back with a no method for nill class error.
Where should I define the article_id? Does it need to go in to migration file for CreateTagging?
The tagging.rb file is your join file, and you have article_id and tag_id defined in there.
I note that you have belongs_to :articles ... you should be using the singular ... belongs_to :article. That's likely why you're failing. Provided you did...
generate model Tagging tag:references article:references
... as the tutorial suggests, that would have automatically created the two id fields for you in the taggings table.
You can confirm that by examining the db/schema.rb

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"}}})

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

Getting a count value between many different models and associations

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.