【问题标题】:Listing all instances of a document model that belongs to user through group relationship通过组关系列出属于用户的文档模型的所有实例
【发布时间】:2012-04-14 07:23:32
【问题描述】:

我基本上按照 ROR 指南http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association 来创建如下所示的关系模型。

由于 through 关联,我认为 @user.trips 会为您提供用户创建的行程和属于该用户的行程。但是,当我在控制台中执行@user.trips.count 时,结果只是用户创建的行程数;通过“组”关联属于用户的行程不计算在内。

问题:如何让我的视图同时显示用户创建的行程和用户通过“组”所属的行程?

用户/show.html.erb

<% unless @user.all_trips.empty? %>
  <% @user.all_trips.each do |trip| %>
     <!-- Content -->
  <% end %>
<% end %>

用户.rb

class User < ActiveRecord::Base
  has_many :group_trips, :through => :groups,
                         :source   => :trip
  has_many :trips, :dependent => :destroy
  has_many :groups

  def all_trips
    self.trips | self.group_trips
  end


end

trip.rb

class Trip < ActiveRecord::Base
  belongs_to :user
  belongs_to :traveldeal
  has_many :groups

  has_many :users, :through => :groups
end

group.rb

class Group < ActiveRecord::Base
  belongs_to :trip
  belongs_to :user
end

谢谢!

编辑:根据 TSherif 的部分解决方案修改代码。 编辑 2:修复了 all_trips 方法。在这一点上,一切似乎都对我有用。

【问题讨论】:

  • 顺便说一句,我认为最好不要在您的问题中过多地更改代码。现在,如果有人遇到与您相同的问题,他们将无法分辨。
  • 下次会记住这一点;我认为如果人们看到一个可行的解决方案会更有帮助。

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


【解决方案1】:

哦!我想我明白你想要做什么以及为什么这是一个问题。我想知道为什么has_many :trips 被称为两次。但据我了解,您有两个 不同 User-Trip 关系。这两个不能同名,否则一个会隐藏另一个。试试这样的:

class User < ActiveRecord::Base
  has_many :group_trips, :through => :groups,
                         :class_name   => "Trip"
  has_many :trips, :dependent => :destroy
  has_many :groups

  def all_trips
    Trip.joins(:groups).where({:user_id => self.id} | {:groups => {:user_id => self.id}})
  end
end

或者,如果您使用的是没有 MetaWhere 的旧版 Rails:

def all_trips
  Trip.joins(:groups).where("(trips.user_id = ?) OR (groups.user_id = ?)", self.id, self.id)
end

【讨论】:

  • 我不确定Rails 3 joins 方法是否可以进行关联。此外,您似乎正在将表达式传递给 where 方法。我在哪里可以阅读有关这些方法的更多信息? api.rubyonrails.org 和 apidoc.com 将 where 方法记录为: where(opts, *rest) 所以我唯一的文档来自 Rails 2.3 find 方法。
  • where 子句中的表达式使用MetaWhere 语法。你可以在这里获取相关信息:erniemiller.org/projects/metawhere
  • 谢谢。我很感激。尽管如此,Rails 文档还是找到所有这些的更好的地方,而不是四处寻找这样的东西。 :)
  • 完全同意。我已经使用 Rails 3 大约一年了,上周在观看 Railscast 时偶然发现了这些东西(顺便说一句,如果你还没有使用它,这是一个很好的资源)。
  • 嗯...所做的只是两个单独查询之间的集合并集。如果你想那样做,就做def all_trips; self.trips | self.group_trips; end。但是你是说friend.all_trips.count 产生的东西与friend.all_trips.all.size 不同吗?您能否发布从第一个查询(来自您的执行日志)生成的 SQL,以便我看一下。我认为它应该工作。寻找带有SELECT COUNT(... 的那个。
猜你喜欢
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多