我基本上按照 ROR 指南http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association创建关系模型,如下所示。
由于直通关联,我认为@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
行程.rb
class Trip < ActiveRecord::Base
belongs_to :user
belongs_to :traveldeal
has_many :groups
has_many :users, :through => :groups
end
组.rb
class Group < ActiveRecord::Base
belongs_to :trip
belongs_to :user
end
谢谢!
编辑:根据 TSherif 的部分解决方案修改代码。编辑 2:修复了 all_trips 方法。在这一点上,一切似乎都对我有用。