Home > database >  Get items with Rails relations
Get items with Rails relations

Time:10-14

I have two models with a relation like this:

class Ticket < ActiveRecord::Base
 belongs_to :group
end
class User < ActiveRecord::Base
 has_and_belongs_to_many :groups
 has_many :tickets, as: :assignable
end
class Group < ActiveRecord::Base
 has_many :tickets, -> { order(:created_at) }
 has_and_belongs_to_many :users
end

I need to get all tickets belonging to the same groups the user has. How can I accomplish that? Thank you so much!

CodePudding user response:

As things stand, your relations are incomplete and so Rails won't work properly. If User has_many Tickets then Tickets must belong_to (or at least has_one) User. Alternatively, User can have_many Tickets through Group, which seems more likely in this case.

However, even then, it's not clear what your Group model is doing. Particularly, it's not clear how you intend it to relate to User - this looks like quite a complex relationship.

To start with, though, try and set the models up like this:

class Ticket < ApplicationRecord
 belongs_to :group
end

class Group < ApplicationRecord
 belongs_to :user
 has_many :tickets, dependent: :destroy
end

class User < ApplicationRecord
 has_many :groups, dependent: :destroy
 has_many :tickets, through: :groups
end

(You'll see that I've also inherited these models from ApplicationRecord, which is how I've always done it.)

If you set it up as above, you can get your ticket records with a simple @user.tickets.

If this works, you can then add the extra HABTM relationship for Groups and Users. But be aware that HABTM relationships can be complex and there are good and bad ways to use them.

(If the primary relationship you really want is Groups > Users > Tickets then let me know and I can adjust accordingly.)

  • Related