Search code examples
ruby-on-railshas-manybelongs-to

Ruby on Rails: listing Products with belongs_to / has_many assosiation


I am trying to built RoR app with Users, Rooms, Products. I'll begin by listing my models below.

class Product < ActiveRecord::Base
 belongs_to :user
 validates :name, :user_id, presence: true
 validates :price, numericality: { greater_than_or_equal_to: 0 }, presence: true
end

class User < ActiveRecord::Base
 has_many :products, dependent: :destroy
 has_many :memberships, dependent: :destroy
 has_many :rooms, through: :memberships
 <...>
end

class Room < ActiveRecord::Base
 has_many :memberships
 has_many :users, through: :memberships
 validates :name, presence: true, length: { in: 6..20 }
end

class Membership < ActiveRecord::Base
 belongs_to :user
 belongs_to :room
 validates :user_id, presence: true
 validates :room_id, presence: true
end

Users can have many Products, they can join/leave Rooms.

I my views I want to show current_user's Room (which has multiple Users who have multiple Products) and list all Products by all Users who are in that Room (and sort by created_at DESC). Could you help me to find a good way of achieving this?

Thanks in advance!


Solution

  • you can use eager_load to load the model associations. This is good starting guide to understand eager_load, includes and joins and their differences.

    Now you use following query for your usecase.

    result = current_user.eager_load(:rooms => [:users => :products ]).order("rooms.created_at DESC")
    

    Hope this helps.