简体   繁体   English

通过关联Rails 2.3.x可以过滤许多记录

[英]filter records in has many through association Rails 2.3.x

I have three models connected via an has_many_through association. 我通过has_many_through关联连接了三个模型。

class Board < ActiveRecord::Base
has_many   :celebrations, :dependent => :destroy
has_many   :users, :through => :celebrations

class User < ActiveRecord::Base
has_many :boards,
         :through => :celebrations
has_many :celebrations, :dependent => :destroy

class Celebration < ActiveRecord::Base
belongs_to :user
belongs_to :board

class CreateCelebrations < ActiveRecord::Migration
  def self.up
   create_table :celebrations do |t|
      t.column :board_id,        :int, :null => false
      t.column :user_id,         :int, :null => false 
      t.column :role,        :string, :null => false
      t.column :token,       :string
      t.timestamps
      end
  end

I would like to get all of the users for a specific board where the role of the user is FRIEND. 我想为一个特定的委员会吸引所有用户,而该用户的角色是FRIEND。 The role is in the Celebrations table. 该角色在Celebrations表中。

I have tried the following in the controller: 我已经在控制器中尝试了以下方法:

@friends = User.condtions(:celebrations => {:role => "FRIEND", :board_id => session[:board_id]})

which results in: 结果是:

NoMethodError in FriendsController#show

undefined method `condtions' for #<Class:0x1023e3688>

I have tried: 我努力了:

@friends = Board.find(session[:board_id]).celebrations.conditions(:role => "FRIEND").joins(:user)

which results in: 结果是:

ArgumentError in FriendsController#show

wrong number of arguments (1 for 0)

How can I get the users who have the rols of FRIENDS for a specific board? 我如何才能获得拥有FRIENDS角色的特定董事会的用户?

Thank you very much in advance. 提前非常感谢您。

This works: 这有效:

board = Board.find(session[:board_id])
@friends = board.users.find(:all, :conditions => ["celebrations.role = ?", "FRIEND"])

I extended the class association in the Board.rb file. 我在Board.rb文件中扩展了类关联。

has_many   :users, :through => :celebrations do
           def by_role(role) #great for returning all of the users whose role is FRIEND
               find(:all, :conditions => ["celebrations.role = ?", role])
               end
           end

And then I can call the following in my controller. 然后,我可以在控制器中调用以下命令。

board = Board.find(session[:board_id])
@friends = board.users.by_role("FRIEND")

Thank to Josh Susser and his blog 感谢Josh Susser和他的博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM