我有三个模型通过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
我想让特定董事会的所有用户都知道用户的角色是FRIEND。角色在庆祝表中。
我在控制器中尝试了以下内容:
@friends = User.condtions(:celebrations => {:role => "FRIEND", :board_id => session[:board_id]})
导致:
NoMethodError in FriendsController#show
undefined method `condtions' for #<Class:0x1023e3688>
我试过了:
@friends = Board.find(session[:board_id]).celebrations.conditions(:role => "FRIEND").joins(:user)
导致:
ArgumentError in FriendsController#show
wrong number of arguments (1 for 0)
如何让具有FRIENDS rols的用户获得特定主板?
非常感谢你。
这有效:
board = Board.find(session[:board_id])
@friends = board.users.find(:all, :conditions => ["celebrations.role = ?", "FRIEND"])
答案 0 :(得分:0)
我在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
然后我可以在我的控制器中调用以下内容。
board = Board.find(session[:board_id])
@friends = board.users.by_role("FRIEND")
感谢Josh Susser和他的blog