Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

ruby on rails - Accessing a relationship through another relationship

I have three models: Trip, Visit, Park

The relationships are currently set up like:

class Trip < ApplicationRecord
    has_many :visits
end

class Visit < ActiveRecord::Base
    belongs_to :park, counter_cache: true
    belongs_to :trip, optional: true
end

class Park < ActiveRecord::Base
    has_many :visits
end

Basically, If I have a trip, what I want to return is a list of Parks visited on that trip.

I could iterate the visits and grab the parks and deduplicate but there's most likely a more "railsy" way to achieve this that I just don't know about.

Any suggestions?

Many thanks.

question from:https://stackoverflow.com/questions/65876413/accessing-a-relationship-through-another-relationship

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need a "has_many through" relationship.

class Trip < ApplicationRecord
    has_many :visits
    has_many :parks, through: :visits
end

class Visit < ActiveRecord::Base
    belongs_to :park, counter_cache: true
    belongs_to :trip, optional: true
end

class Park < ActiveRecord::Base
    has_many :visits
end

You only have to add has_many :parks, through: :visits in Trip model. Then from Trip you can access to all parks using the parks relation.

https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...