Rails:创建嵌套视图

时间:2011-04-17 11:55:40

标签: ruby-on-rails ruby-on-rails-3

我正在尝试做一份报告,向旅行者展示他们的哪些银行卡可以在哪些国家/地区使用。

对于指定的目的地国家/地区(例如泰国),我想在以下分组中列出所有卡<> atm_matches 来源国<机构<卡< Card_match.atm.name

我有以下数据模型

Country
-< Institution -< Card -< Card_Match
-< Atm -< Card_Match

以下是模型,首先是数据模型的第一行:

class Country < ActiveRecord::Base
  has_many :institutions, :dependent => :destroy
  accepts_nested_attributes_for :institutions

  has_many :atms, :dependent => :destroy
  accepts_nested_attributes_for :atms
  has_many :card_matches, :through => :atms
end

class Institution < ActiveRecord::Base
  belongs_to :country
  has_many :cards, :dependent => :destroy
  accepts_nested_attributes_for :cards
end

class Card < ActiveRecord::Base
  belongs_to :institution
  has_many :card_matches, :dependent => :destroy
  accepts_nested_attributes_for :card_matches, :allow_destroy => true
end

现在是下腿(Atm):

class Atm < ActiveRecord::Base
  belongs_to :country
  has_many :card_matches, :dependent => :destroy
  accepts_nested_attributes_for :card_matches, :allow_destroy => true
end

Card_Matches加入两条腿:

class CardMatch < ActiveRecord::Base
  belongs_to :card
  belongs_to :atm
end

使用Country.find(:id).card_matches我通过atm关联获取目的地国家/地区的所有card_matches。但是我不确定如何从那里向后构建以获得Source Country&gt;机构&gt;卡片分组我需要。

有没有办法从嵌套关系链的一条腿的底部的连接表中获取一个列表,并向后向上工作显示信息的另一条腿?像@ matchList.cards.instititions.countries.name这样的东西(顺便给出错误)。或者(低效)SQL:

mysql> select name from countries where id in (select country_id from institutions where id in
    -> (select institution_id from cards where id in
    -> (select card_id from card_matches where atm_id in
    -> (select id from atms where country_id = 2))));

或者我应该尝试以另一种方式做这些事情?提前谢谢。

0 个答案:

没有答案