0

我有一个带有以下部分的 Rails 控制器:

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

sort_column并且sort_direction被定义为 (@player_to_team_histories是一个ActiveRecordAssociation:

private

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

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

所以从这两个函数返回的文本被插入order@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)andsort_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

但这仍然不起作用(我将对函数的调用更新为没有params)。

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

导轨 3.2.1,红宝石 1.9.2

4

1 回答 1

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
于 2012-11-15T03:36:34.983 回答