【问题标题】:Adding two table columns for sorting添加两个表格列进行排序
【发布时间】:2011-08-04 01:25:34
【问题描述】:

我正在使用 Ruby on Rails (3.0) 构建任务管理应用程序。我有项目和任务。任务属于_to 项目和项目有_许多任务。

我的任务表有 position、project_position 和 priority 列。当通过 AJAX 移动可排序列表时,位置列会更新。当项目通过可排序列表和 AJAX 排序时,project_position 列会更新。我希望优先级列是 position 和 project_position 的总和,以便我可以:order => "priority"。

有什么想法吗?

更新:

不确定以下代码是否妨碍您:

projects_controller.rb

  def sort
    params[:projects].each_with_index do |id, index|
      Project.update_all(['position=?', index+1], ['id=?', id])
    end
    render :nothing => true
  end

tasks_controller.rb

  def sort
    params[:tasks].each_with_index do |id, index|
      Task.update_all(['position=?', index+1], ['id=?', id])
    end
    render :nothing => true
  end

【问题讨论】:

    标签: ruby-on-rails ruby sorting associations


    【解决方案1】:

    我会通过before_save 回调来做到这一点。

    class Task < ActiveRecord::Base
      before_save :set_priority
    
      protected
    
      def set_priority
        self.priority = self.project_position + self.position
      end
    end
    

    如果您按照我的其他建议将delegate 职位从任务转移到项目,那么您可能需要/需要在此处进行一些额外的检查,以确保任务是通过项目构建或创建的,因为如果不是委托的 project_position 将返回nil,当您尝试添加它时会出现错误。

    您还需要继续使用 Project 上的 after_save 回调,以便重新保存所有任务,从而更新它们在数据库中的优先级值。

    class Project < ActiveRecord::Base
      after_save :set_task_priorities
    
      protected
    
      def set_task_priorities
        self.tasks.each(&:save)
      end
    end
    

    【讨论】:

    • 好吧,这真是很棒的东西。关于这个和另一个问题。有了您的所有建议,我收到了一个错误nil can't be coerced into Fixnum,这是指self.priority = self.project_position + self.position 行。有什么想法吗?
    • 我的猜测是set_priority 方法正在尝试添加self.position,但尚未设置自身位置,因此它为零。听起来对吗?
    • 嘿,抱歉耽搁了。是的,nil can't be coerced 消息是关于尝试向 nil 添加一个数字。这就是我在上面的“一点额外检查”注释中所指的内容,这取决于您如何构建任务/项目对象。如果还没有项目可供任务参考,那么您将从委托方法中得到一个 nil,并且您不能在数学上添加 nil。一个简单的解决方案是:self.priority = (self.project_position ? self.project_position : 0) + self.position。通过这种方式,如果 project_position 存在则添加,如果不存在则添加 0。
    • 或者,self.priority = (self.project_position || 0) + self.position
    • 感谢您继续提供帮助。我尝试了您提供的两行代码,虽然它不会导致错误,但任务中的所有列(位置、优先级和项目位置)都设置为 [Null]。
    猜你喜欢
    • 2012-11-20
    • 2012-10-20
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多