调用方法在Rails模型中提供搜索参数

时间:2012-11-15 03:21:05

标签: ruby-on-rails activerecord model controller

我有一个Rails控制器,包含以下部分:

def search
  ...
  @player_to_team_histories = @player_to_team_histories.order(sort_column + " " + sort_direction)
  ...

sort_columnsort_direction定义为(@player_to_team_historiesActiveRecordAssociation

private

  def sort_column
    params[:sort] || "players.LastName"
  end

  def sort_direction
    params[:direction] || "asc"
  end

因此,从这两个函数返回的文本将被插入到order的{​​{1}}子句中。

我需要在另一个控制器中复制此搜索功能,因此我已将搜索逻辑移至@player_to_team_histories模型,并将PlayerToTeamHistories哈希作为参数传递给params函数。骨架代码:

search

我尝试在模块中定义def self.search_results(params) ... @player_to_team_histories = @player_to_team_histories.order(sort_column(params) + " " + sort_direction(params)) ... sort_column(params)并且不断收到sort_direction(params)错误,因此我将实现移到了模型的底部

undefined method or variable sort_columns

仍然会得到未定义的方法错误。我尝试将其简化为:

def sort_column(params)
  params[:sort] || "players.LastName"
end

def sort_direction(params)
  params[:direction] || "asc"
end

但是仍然没有用(我将函数调用更新为def sort_column "players.LastName" end def sort_direction "asc" end )。

知道为什么我不能从模型中的另一个函数中调用辅助函数吗?

Rails 3.2.1,Ruby 1.9.2

1 个答案:

答案 0 :(得分:1)

如果方法在模型中 - 它们就是实例。你应该把它们称为:

def self.search_results(params)
 ...
  @player_to_team_histories = @player_to_team_histories.order(@player_to_team_histories.sort_column + " " + @player_to_team_histories.sort_direction)
 ...
end