first_or_initialize不适用于相对模型并且每次都创建新记录

时间:2016-11-16 13:13:06

标签: ruby ruby-on-rails-3 ruby-on-rails-4

ccs.each do |cd|
  relative_model = main_model.relative_model.where(start_date: XYZ, end_date: XYZ).first_or_initialize
  relative_model.capacity = cd['capacity'].to_f
  relative_model.save!
end

根据上面的代码,first_or_initialize不适用于相对模型并且每次都创建新记录。

以下是inr的后台运行查询:

SELECT `capacity_commitments`.* FROM `capacity_commitments`  WHERE `capacity_commitments`.`participants_subscription_id` = 1 AND `capacity_commitments`.`start_date` = '2016-11-16' AND `capacity_commitments`.`end_date` = '2016-11-21'

SELECT `capacity_commitments`.* FROM `capacity_commitments`  WHERE `capacity_commitments`.`participants_subscription_id` = 1 AND `capacity_commitments`.`start_date` = '2016-11-16' AND `capacity_commitments`.`end_date` = '2016-11-21'

需要初步帮助或指出上面的代码有什么错误?

1 个答案:

答案 0 :(得分:1)

尝试使用find_or_initialize_by方法

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        Graphics graphic = this.CreateGraphics();
        graphic.DrawLine(Pens.Black, e.X, e.Y, e.X + 1, e.Y + 1);
    }

    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        Graphics graphic = this.CreateGraphics();
        graphic.DrawLine(Pens.Red, e.X, e.Y, e.X + 1, e.Y + 1);
    }
}