Forum: Ruby on Rails belongs_to :through

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wiktor -. (Guest)
on 2006-04-25 14:01
belongs_to :through

Why is that not possible?

We should have:

Street
belongs_to :city
belongs_to :country, :through => :city
Wiktor -. (Guest)
on 2006-04-26 02:12
Wiktor  wrote:
> belongs_to :through
>
> Why is that not possible?
>
> We should have:
>
> Street
> belongs_to :city
> belongs_to :country, :through => :city


Anyone?
Josh S. (Guest)
on 2006-04-26 04:37
Wiktor  wrote:
> belongs_to :through
>
> Why is that not possible?
>
> We should have:
>
> Street
> belongs_to :city
> belongs_to :country, :through => :city

I don't see how that would get you much. You can simulate the convenient
access to the country by delegating to the city, and if you are
concerned about double queries, just use an :include on city to fetch
the country at the same time.

Street
  belongs_to :city, :include => :country
  delegate :country, :country=, :to => :city

--
Josh S.
http://blog.hasmanythrough.com
Wiktor -. (Guest)
on 2006-04-26 10:02
Josh S. wrote:
> Street
>   belongs_to :city, :include => :country
>   delegate :country, :country=, :to => :city


Josh,

It is awesome, thanks. That's what I was looking for. Now, maybe you
would be able to help me also with opposite problem:

class Country < ActiveRecord::Base

  has_many :states
  has_many :cities, :through => :states
  has_many :streets, :through => :cities

It doesn't work...
I wan't to use country.streets(...)

I was trying to use :finder_sql => 'SELECT streets.* FROM states,
cities, streets WHERE states.country_id = #{id} AND cities.state_id =
states.id AND streets.city_id = cities.id' but I get an error:

Mysql::Error: #21000Operand should contain 1 column(s): SELECT * FROM
streets WHERE (SELECT streets.* FROM states, cities, streets WHERE
states.country_id = 1 AND cities.state_id = states.id AND
streets.city_id = cities.id) AND (streets.`subdomain` = 'test' )  LIMIT
1

When using:
@country.streets.find_by_subdomain(@sub.first)
Wiktor -. (Guest)
on 2006-06-07 02:56
> class Country < ActiveRecord::Base
>
>   has_many :states
>   has_many :cities, :through => :states
>   has_many :streets, :through => :cities
>
> It doesn't work...

Anyone?
This topic is locked and can not be replied to.