Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为rails中的列创建动态默认值?_Ruby On Rails_Postgresql_Callback_Migration_One To Many - Fatal编程技术网

Ruby on rails 为rails中的列创建动态默认值?

Ruby on rails 为rails中的列创建动态默认值?,ruby-on-rails,postgresql,callback,migration,one-to-many,Ruby On Rails,Postgresql,Callback,Migration,One To Many,我不知道该怎么做,或者是否有更好的方法,但我有一个名为leads(many)的表,它引用了agent(one) 我想进行迁移,为leads表中的agent_id列设置默认值。但是我希望默认值在所有代理ID之间循环。我不知道怎么做!?我应该使用回调,还是应该在迁移文件中使用回调 以下是我试图解决的实际问题: 创建新潜在客户时,使用“循环”将其分配给代理,这样新潜在客户将均匀分布在所有代理上 我附上了一个屏幕截图,使用SUDO代码(我知道它没有功能)来说明我在想做什么。有什么建议吗 (使用Rubyo

我不知道该怎么做,或者是否有更好的方法,但我有一个名为leads(many)的表,它引用了agent(one)

我想进行迁移,为leads表中的agent_id列设置默认值。但是我希望默认值在所有代理ID之间循环。我不知道怎么做!?我应该使用回调,还是应该在迁移文件中使用回调

以下是我试图解决的实际问题:

创建新潜在客户时,使用“循环”将其分配给代理,这样新潜在客户将均匀分布在所有代理上

我附上了一个屏幕截图,使用SUDO代码(我知道它没有功能)来说明我在想做什么。有什么建议吗

(使用RubyonRails和postgresql)


我认为将此功能作为主应用程序的一部分处理是有意义的,而不是在迁移中处理,因为似乎有大量功能需要处理

最好在
Lead
模型中创建
后将其作为
回调的一部分进行处理,并使用类变量跟踪下一个要分配的代理,如下所示:

class Lead
  # Assign the class variable to the first agent
  @@next_agent = Agent.first
  after_create :set_agent

  ...

  private

  # Called by the after_create callback
  # Sets the agent_id, and updates the @@next_agent class variable
  def set_agent
    self.agent_id = @@next_agent.id
    @@next_agent = find_next_agent
  end

  ## Called from the set_agent method
  ## Finds the next agent based on the current value of @@next_agent
  def find_next_agent
    @@next_agent = Agent.find(@@next_agent.id + 1)
    @@next_agent = Agent.first unless @next_agent
  end
end

上面的
find_next_agent
逻辑是一个简单的示例,假设所有代理对象的ID增量为1,并且没有间隙(即表中没有删除)

所以每个
潜在客户
都应该有唯一的
代理
?这正是我要找的!关于您提出的解决方案,我有一些后续问题:-为什么对@next\u代理使用类变量而不是实例变量-为什么要使用after\u create:set\u agent而不是before\u create:set\u agent,就像之前的\u create一样?它必须是类变量,而不是实例变量,因为它必须在实例之间是唯一的。实例变量的值对于每个实例都不同。无论从哪个实例访问,类变量都将具有相同的值。