麻烦搞定加入协会

时间:2012-03-03 18:15:52

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

我有帐户,门票,小组:

# group.rb
has_many :tickets
has_many :accounts, :through => :assignments
has_many :assignments

# ticket.rb
belongs_to :group, :class_name => "Group", :foreign_key => "group_id"
has_many :accounts , :through => :assignments
has_many :assignments

# account.rb
attr_accessible :first_name, :last_name, :email, :password, :group_ids, :role
has_many :tickets, :through => :assignments
has_many :assignments    
has_many :groups, :through => :assignments
has_many :assignments

#assignment.rb
belongs_to :account
belongs_to :ticket
belongs_to :group

我想列出其组属于current_account的{​​{1}}的票据。

出于某种原因,它整天都在让我的大脑难以理解,看起来它应该非常简单,但我无法弄明白。

更新

我也为Ticket模型命名了范围:

group_id

所以我需要能够将 scope :not_archived, where('archived != ?', 1) scope :is_archived, where('archived = ?', 1) .not_archived添加到。{所以不确定@Veraticus答案是否有效。

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西:

current_account.groups.collect(&:tickets)

这将返回附加到current_account组的所有票证阵列的数组。如果你想把它当作一个大数组,你可以在最后调用flatten:

current_account.groups.collect(&:tickets).flatten

如果你有适用范围,我会做这样的事情:

current_account.groups.collect{|g| g.tickets.not_archived.all}.flatten

用你想要的任何东西替换范围。

答案 1 :(得分:0)

您可以在以帐户作为参数的故障单上创建命名范围:

#ticket.rb
scope :for_account lambda { |account| joins(:group => :accounts ).where("accounts.id = ?", account.id) }

应生成sql,如:

SELECT ticets.* FROM ticket
INNER JOIN groups ON tickets.groups_id = groups.id
  INNER JOIN accounts ON groups.account_id = accounts.id
WHERE accounts.id = x

然后你可以打电话:

Ticket.for_account(current_account)

要获取当前帐户的门票,它会在一个查询中全部拉出来。然后,您可以将此链接到您想要的任何其他范围,例如。

Ticket.not_archived.for_account(current_account)