简体   繁体   中英

Rails, active record. Joining four tables together

I am learning ruby on rails and I've run into an active record problem I have been unable to solve. I am trying to inner join four tables together and display data from them.

I have confirmed that my database schema is correct by running the following SQL style query. It returns the data I expect it to.

 select * from sailings
 INNER JOIN travelling_parties on sailings.id = travelling_parties.sailing_id
 INNER JOIN party_registers on travelling_parties.id = party_registers.travelling_party_id
 inner JOIN users on party_registers.user_id = users.id
 where users.id = 8

After reading through the great docs on guides.rubyonrails.org, I am still unable to find the solution. The below query is what I've come up with in my controller, but it doesn't seem to be return what I need it to.

@sailing = Sailing.joins(:travelling_parties => [{:party_registers => :user}])

I would appreciate anyone who could steer me in the right direction.

Thanks

EDIT 1: Here are my models. I am attempting to check user.id = current_user.id and display data based on that.

class Sailing
  has_many :travelling_parties
end

class TravelingParty
  has_many :party_registers
  has_many :users, through: :party_registers
end

class PartyRegister
  belongs_to :user
  belongs_to :travelling_party
end

class User
  has_many :party_registers
  has_many :travelling_parties, through: :party_registers
end

EDIT 2: The following query gave me my intended results

@sailing = Sailing.joins(:travelling_parties => {:party_registers => :user}).where("users.id" => current_user.id)

Thanks for the responses.

Your answer is close to correct assuming that you have defined the associations.

class Sailing
  belongs_to :traveling_party
end

class TravelingParty
  belongs_to :party_register
end

class PartyRegister
  belongs_to :user
end

The

@sailing = Sailing.joins(:travelling_parties => {:party_registers => :user})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM