Conditions on has_many through - mysql

I have three classes
TeamMember, Service and ServiceTeamMember
I have
class Service
has_many :service_team_members
has_many :team_members, through: :service_team_members
end
class ServiceTeamMember
belongs_to :service
belongs_to :team_member
end
class TeamMember
has_many :service_team_members
has_many :services, through: :service_team_members
end
Now in a certain area of my site I want to eager load departments, where a department is a top level service, I'm using ancestry so all you need to know is a department is a service with ancestry of NULL
So I need an actual association so I can eager load it rather than a scope.
I've tried adding it as such
has_many :departments, -> { where(ancestry: nil) }, through: :service_team_members, source: :service
But I get the following error
Mysql2::Error: Unknown column 'services.ancestry' in 'where clause': SELECT `service_team_members`.* FROM `service_team_members` WHERE `services`.`ancestry` IS NULL AND `service_team_members`.`team_member_id` IN (28, 32)
So rails is applying my condition to the join table rather than the table I want. How can I get around this, I assume it's a simple solution and I'm missing something obvious.

Just change source: :service by source: :team_member

Related

How to make associations on this

Hello, i'm new to rails. I have been fed up with active record associations. I did study associations from the rails guides. Yet i cant find myself a clear way to add associations to the models suggested in the diagram.
I have one doubt whether a single foreign key(SECOND MODEL) can reference two primary keys (SECOND MODEL LEVEL 2 FIRST & SECOND MODEL LEVEL 2 SECOND). This has been done because the user has to choose whether to add from the SECOND MODEL LEVEL 2 FIRST TABLE or the SECOND MODEL LEVEL 2 SECOND TABLE while inserting values into the SECOND MODEL.
If u find this hard to understand please leave a comment, ill make appropriate changes. And i would appreciate on how to query from the FINAL LEVEL FIRST with BASE-MODEL thorough a join condition.
You can use polymorphic association to refer to one table OR another, check the model below as per the posted image:
class BaseModel
has_many :first_models
has_many :second_models
end
class FirstModel
belgons_to :base_model
has_one :level_two_first_model
end
class LevelTwoFirstModel
belgons_to :first_model
end
class SecondModel
belgons_to :base_model
has_many :final_first_levels, as: :referenceable, :dependent => :destroy
has_many :final_second_levels, as: :referenceable, :dependent => :destroy
end
class LevelOneSecondModel
belongs_to :referenceable, polymorphic: true
has_many :final_first_levels
end
class LevelTwoSecondModel
belongs_to :referenceable, polymorphic: true
has_many :final_first_levels
end
class FinalFirstLevel
belongs_to :LevelOneSecondModel
end
class FinalSecondLevel
belongs_to :LevelTwoSecondModel
end
referenceable is used as the glue between the parent table and other polymorphic associations (LevelOneSecondModel OR LevelTwoSecondModel)
NB:
Don't forget to add the below line in the migration files of the 2 children tables used in polymorphic association.
t.references :referenceable, polymorphic: true, index: true
Reference:
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

How to sort nested items on field in 'parent' model?

I am new to Ruby on Rails and try to make the right query. But after reading the documentation and examples I don't manage to get the right query out of it. So I hope someone can point me in the right direction.
Situation I build an app where trainers can setup trainings, and give these trainings on several dates (the dates are called thrills), other users can subscribe for these thrills. It has the following structure:
class User
has_many :trainings
has_many :thrills, through: :trainings
has_many :reservations
class Training
belongs_to :user
has_many :reservations
has_many :thrills
has_many :users, through: :thrills
class Thrill
belongs_to :training
has_many :reservations
has_many :users, through: :reservations
class Reservation
belongs_to :user
belongs_to :thrill
has_one :training, through: :thrill
Question
How can I make a list of all reservations of the current_user ordered by the thrilldate? The thrilldate is set in the Thrills model.
In my reservations_controller.rb I have:
#reservations = current_user.reservations
This gives the right list of all the reserations, but I want to sort list this on reservation.thrill.thrilldate
I tried so by using this view:
<% #reservations.order("reservation.thrill.thrilldate ASC").each do |reservation| %>
Unfortunately this gives the error:
SQLite3::SQLException: no such column: reservation..thrill.thrilldate: SELECT
"reservations".* FROM "reservations" WHERE "reservations"."user_id" =
? ORDER BY reservation.thrill.thrilldate ASC
Who knows how I can refer to the thrilldate in the Thrills model? Thanks for helping me out!
Assuming thrilldate is a column on Thrill
#reservations = current_user.reservations.joins(:thrill).order('thrills.thrilldate asc')

Query in Ruby on Rails 4 to make a selection based on the current user

I am new to Ruby on Rails and try to make the right query. But after reading the documentation and examples I don't manage to get the right query out of it. So I hope someone can point me in the right direction.
Situation
I build an app where trainers can setup trainings, and give these trainings on several dates (the dates are called thrills), other users can subscribe for these thrills. It has the following structure: models and needed table.
My models code looks like this:
class User
has_many :trainings
has_many :thrills, through: :reservations
has_many :reservations
class Training
belongs_to :user
has_many :reservations
has_many :thrills
has_many :users, through: :thrills
class Thrill
belongs_to :training
has_many :reservations
has_many :users, through: :reservations
class Reservation
belongs_to :user
belongs_to :thrill
has_one :training, through: :thrill
On an index page I want to show all the thrills that the current user has setup sorted by date. I think I need a query that comes up with the table in the uploaded image, and from that table I can select all Thrills where current_user.id = user_id
On the search page I want to show only the trainings that have a Thrill that is not full (therefore I want to make a count of the Reservations)
I was thinking of something like this:
#thrills = Thrill.joins(:trainings).where('? = trainings.user_id, current_user.id')
or
#thrills = Thrill.where('? = #thrill.training.user_id', current_user.id).all
or
#thrills = Thrill.joins(:trainings).where(trainings: { user_id: current_user.id })
But unfortunately none of them works. Does someone have an idea how to solve this? Thanks in advance!
Usually you have these two models:
class Thrill < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :thrills
end
So for your index page what you can do is:
current_user.thrills # => ActiveRecord::Relation (can call each, map etc.)

Multiple Foreign Keys with Ruby on Rails

I have the following setup:
One matchdays table with a column called home_team_id and one called visitor_team_id
and a team table.
My Match model looks like this:
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: "Team", foreign_key: :home_team_id
belongs_to :visitor_team, class_name: "Team", foreign_key: :visitor_team_id
belongs_to :matchday
validates :home_team, presence: true
validates :visitor_team, presence: true
end
And the Team model like that:
class Team < ActiveRecord::Base
has_many :matches
has_many :player
end
Now it's getting tricky (at least for me). I'd like to be able to call team.matches and get all of the matches for the team. Since every team has home games and also games on the road.
Currently I'm getting a ActiveRecord::StatementInvalid Error because it's looking for the team_id column in the matches table.
So if I understand correctly, what you need is just a method that returns all games where the current team is playing. This should do the trick:
class Team < ActiveRecord::Base
has_many :player
def matches
Team.where(home_team_id => self.id, foreign_key => self.id)
# This line will also work if you want to try it out.
# Team.where("home_team_id = ?", self.id).where("foreign_key = ?", self.id)
end
end
Happy coding!

How to add a new attribute to Associate Table column in rails

In my rails application, I had to add a new column named is_leader for an association table.
The relationship for the association table is as follows:
has_and_belongs_to_many :analysis_responses, :join_table => "analysis_responses_participants"
Following is the code where the participant details have been saved to the db:
organization.people.create(participant)
the participant has got the following values
name: Test User
position:
birthdate:
id:
lead: "1"
If the lead value is 1, the is_leader column value should be 1 for the particular record.
I wanted to know how can I save the is_leader value in that association table in rails
Thanks
If you need to save attributes on the join table, then you will have to use a join model instead of a HABTM.
class Organization
has_many :analysis_responses
has_many :people, through: :analysis_responses
end
class AnalysisResponse
belongs_to :organization
belongs_to :person
end
class Person
has_many :analysis_responses
has_many :organizations, through: :analysis_reponses
end