【问题标题】:filter records in has many through association Rails 2.3.x过滤记录中有很多通过关联 Rails 2.3.x
【发布时间】: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


【解决方案1】:

我在 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

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多