如何使用Rails3以优雅的方式找到多对多关系?

时间:2011-02-01 12:14:34

标签: ruby-on-rails-3

我有一个带

的User类
class User < ActiveRecord::Base
  has_many :forum_subscriptions
  has_many :forums, :through => :forum_subscriptions

的论坛课程
class Forum < ActiveRecord::Base
  has_many :users

我想找到订阅论坛“sport”,论坛“TV”和论坛“Hobby”的所有用户 最优雅的方式是什么?

(我脑子里有很多丑陋的东西:-)

1 个答案:

答案 0 :(得分:0)

我将使用以下内容:

User.joins(:forums).where("forums.title IN (?)", %w(sport TV Hobby)).group("users.id")

我认为论坛标题的专栏是'标题'。当您使用其他名称时更改它。您可以将其放在用户模型中的一个很好的范围内,以使其更具动态性。

scope :subscribed_to, lambda { |forum_titles| joins(:forums).where("forums.title IN (?)", forum_titles).group("users.id") }

现在您可以在Controller或其他地方调用此范围:

User.subscribed_to(%w(sport TV Hobby)) # => Get all users that are subscribed to sport, TV and Hobby
User.subscribed_to(["sport", "TV", "Hobby"]) # => Does the same
User.subscribed_to(%w(Hobby)) # => Get all users that are subscribed to Hobby
User.subscribed_to("Hobby") # => Does the same

我认为你有以下关系:

class User < ActiveRecord::Base
  has_many :forum_subscriptions
  has_many :forums, :through => :forum_subscriptions
end
class Forum < ActiveRecord::Base
  has_many :forum_subscriptions
  has_many :users, :through => :forum_subscriptions
end
class ForumSubscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :forum
end

希望这是你所需要的。 :)