【发布时间】:2011-07-13 05:50:06
【问题描述】:
我通过 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 的特定版块的所有用户。该角色在Celebrations 表中。
我在控制器中尝试了以下操作:
@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 角色的用户?
非常感谢您。
这行得通:
board = Board.find(session[:board_id])
@friends = board.users.find(:all, :conditions => ["celebrations.role = ?", "FRIEND"])
【问题讨论】:
-
你有一个错字“条件”应该是“条件”
标签: sql ruby-on-rails filtering has-many-through