ActiveRecord - Display columns from multiple associations - ruby-on-rails-4

I have a user, user_profile and profile_type models. A user has_many user_profiles, a user_profile belongs_to a user and belongs_to a profile_type and a profile_type has_many user_profiles.
I have been reading on how to get this work but I am having problems figuring this out and any help would be much appreciated.
I know I could do this with SQL with a statement like this (freehand SQL, excuse mistakes), but I want to use ActiveRecord.
Select up.id, u.user_id, pt.connection_type
from user u
join user_profile up
on u.user_id = up.user_id
join profile_type pt
on pt.profile_type_id = up.profile_type_id
where u.username = "test"
I want to return nested user_profile objects for an associated user but I want the user_profile object to contain the profile_type.connection_type instead of the profile_type.profile_id.
Currently, if I do this,
user.user_profiles.all
add then iterate through the nested user_profiles that are returned, this is my output:
{
:id
:user_id
:profile_type_id
}
What I want is:
{
:id
:user_id
:profile_type.connection_type (instead of profile_type.profile_type_id)
}
User Model
class User < ActiveRecord::Base
has_many :user_profiles, autosave: true
has_many :account_settings, autosave: true
end
User_Profile Model
class UserProfile < ActiveRecord::Base
belongs_to :user
belongs_to :profile_type
end
User Profile Type Model
class ProfileType < ActiveRecord::Base
has_many :user_profiles
end

Try this:
user.account_settings.select("profile_type.*, profile_type.connection_type").all

I was able to figure out how to do this using Grape.
Since the association was already created, I can use Grape entities to expose what I needed out of the associations. It works seamlessly and I hope this helps anyone else who is having a similar problem.
To get what I was looking for, I needed to gather all user_profiles
userprofiles = user.user_profiles.all
Then, I presented this using Grape
present :user_profile_settings, userprofiles, with: API::V1::Entities::UserProfile
And, here is what my entities looked like:
class UserProfile < Grape::Entity
expose :profile_type, using: ProfileTypeEntity
end
class ProfileTypeEntity < Grape::Entity
expose :connection_type
end

Related

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.

Access rails model attributes through a has one association

My User has one Driver:
class User < ActiveRecord::Base
has_one :driver, :dependent => :destroy
end
class Driver < ActiveRecord::Base
belongs_to :user
end
User attributes include, user_first_name, user_last_name, user_email and user_phone number.
I want to be able to access these User attributes when working with the driver class.
For example:
#drivers = Driver.where( :user_first_name => "David )
Obviously the above code won't work, since user_first_name is not a Driver attribute, but is there a way to do this without looping through each user record?
I'm still new to Rails but hopefully this is helpful!
If you create a foreign key index to associate your model's tables within the database, then you should be able to access the data like so...
#user = User.find(params[:id])
#drivers = Driver.where( #user.user_first_name => "David" )
Also, not sure if it was a typo here, but you forgot to close the quotes with "David.

Overriding the embed_key in Active Model Serializer

I have a serializer with some has_many associations where I've modified the embed_key.
I'm trying to have the IDs for my model be like path-name rather than 12. The code below is making that happen:
class SymbolSerializer < ActiveModel::Serializer
attributes :id,
:name,
:parent_id,
:rails_id
embed :ids, include: true
has_many :ancestors, embed_key: :symbol_path, serializer: SimplifiedSymbolSerializer
has_many :children, embed_key: :symbol_path, serializer: SimplifiedSymbolSerializer
has_one :parent, embed_key: :symbol_path, serializer: SimplifiedSymbolSerializer
has_many :siblings, embed_key: :symbol_path, serializer: SimplifiedSymbolSerializer
def id
object.symbol_path
end
def parent_id
object.id
end
def rails_id
object.id
end
end
The problem is that I'd like to still have the actual id of the parent object (Which I've tried to do in my parent_id method ^^).
Right now the overridden method still returns the :symbol_path key rather than the id.
Anyone know how to address this?
The simplest way for me to address this was to just use a different naming convention for the key I wanted to pass.
So all I had to do was add this method/attribute in there too:
def parent_rails_id
object.parent.id
end

rails application undefined method for class

I rewrote my create function in my scaffold Review after making it associated with my Concert model. When I try to submit a form to create a review though I get an error saying
undefined method `reviews' for #Class:0xab9972c>
def create
#review = Concert.reviews.create(review_params)
end
My Concert model looks like this
class Concert < ActiveRecord::Base
validates_presence_of :artist
validates_presence_of :venue
validates_presence_of :date
has_many :reviews
end
and my Review model looks like this
class Review < ActiveRecord::Base
validates_presence_of :artist
validates_presence_of :venue
validates_presence_of :date
belongs_to :user
belongs_to :concert
end
I also added the relations within my migration files but I still get the error. Can someone explain to me what is causing this and how I could go about creating a review that belongs to a concert?
The association has_many :reviews is an instance method. I suspect that in your create method you want something like this:
def create
#concert = Concert.new
#concert.save
#review = #concert.reviews.create(review_params)
end

Rails collection_select passing id

I've read a bunch of questions but none of them are helping me with this problem. I am trying to create a form to make new forums but cannot get them to use the right category id.
<%= f.collection_select :category_id, Category.all, :id, :name %>
This creates a new forum but the id is not the category id from the drop down list. Here is the forums model
def new
#forum = Forum.new
end
def create
#forum = Forum.new(forum_params)
if #forum.save
redirect_to root_url
else
render 'new'
end
end
private
def forum_params
params.require(:forum).permit(:category_id, :name, :description )
end
end
Not quite sure what I am doing wrong here. Is it something to do with the foreign key? Any help would really be appreciated.
UPDATE
Forum Model
class Forum < ActiveRecord::Base
belongs_to :category
has_many :topics, dependent: :destroy
end
Category Model
class Category < ActiveRecord::Base
has_many :forums, dependent: :destroy
end
There is basically no category_id in the Forum model.
Here is a couple of things you can do to troubleshoot this. Run:
rails dbconsole
.schema
Check to see if you have category_id or not. If not, create a new migration for this.
Your initial code is correct. For some reason, I misread that your collection_select was already bound to the model.