filter records in has many through association Rails 2.3.x
I have three models connected via an has_many_through association.
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. The role is in the Celebrations table.
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?
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.
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
精彩评论